Search code examples
haskellfoldstate-monad

Haskell foldl Monad bind


I got a function

move :: Move -> Node -> Maybe Node

where I can use my bind monad to obtain a Maybe Node

(return n >>= move m) 

where n::Node and m::Move, but how I can now fold through a list of Moves ([Move])?

I tried to do it with foldl but without success.


Solution

  • If you have an initial Node and a [Move] you can use foldM:

    moveAll :: Node -> [Move] -> Maybe Node
    moveAll startNode moves = foldM (\n m -> move m n) startNode moves
    

    or simply

    moveAll = foldM (flip move)