I’m implementing a combinatorial optimization algorithm in Haskell:
Given an initial candidate solution, repeat until stopping criteria are met:
1. Determine possible moves
2. Evaluate possible moves
3. Choose a move
4. Make move, record new candidate solution, update search state
I could write functions for steps 1-4 and chain them together inside a recursive function to handle looping and passing state from one iteration to the next, but I have a vague idea that monads apply.
What’s the best way to express this kind of procedure in Haskell?
The best way to express this sort of iterative procedure in Haskell is as an infinite list of each successive result. Piecing together your four steps yields a notion of a function from a solution to a different (better) solution; all you need to do is apply this infinitely many times. The user of your function can then use any list function to get the answer:
solve s0 !! numIterations, orfind stoppingCondition $ solve s0, or whatever you want.In order to get here, let’s write out the types for each of these functions.
moves :: Solution -> [Move]Given a possible solution, figure out the possible changes you can make.
value :: Solution -> Move -> DoubleGiven a solution and a move, evaluate it and record that value as some real number.
choose :: Solution -> [Move] -> MoveGiven a solution and a list of moves, pick the best one.
apply :: Solution -> Move -> SolutionGiven a move, apply it to an existing solution to get a new one.
You want to write a function with a type something like
solve :: Solution -> (Solution -> Bool) -> Solutionwhich takes an initial solution and a stopping condition to execute your algorithm.Instead, let’s make this an infinite list; this means that you’ll just remove the predicate and have
Solution -> [Solution].Here, the key is
iterate :: (a -> a) -> a -> [a], which repeatedly applies a function to a value and gives you the results—exactly the description of your algorithm.However, the way I’d really write this would be the following:
The advantage of this is that you can reuse this same generic structure for any problem domain. All you need to do is to provide the
moves,value, andapplyfunctions! And depending on my mood, I might rewrite that as this:Here, we use applicative notation to say that we’re effectively just doing
(.) apply choose moves(which is justapply . choose $ moves) in a context where each of those functions is implicitly passed a parameters(the reader applicative). If we really wanted to tersify things, we could writeAny of these snippets will do exactly what you need. (Proviso: there are no effects/monads in any of your functions, so randomness is out. You make this monadic easily, though.)
Just for kicks, though, let’s think about the
Statemonad. This represents a computation with some sort of environment, so thatState s ais isomorphic tos -> (a,s)—something which can see the state and potentially update it. Here, all theSolution ->s on the left of your function signatures would disappear, as would the-> Solutions on the right. That would leave you withmoves :: State Solution [Move]value :: Move -> State Solution Doublechoose :: [Move] -> State Solution Moveapply :: Move -> State Solution ()This means that you would have some monadic action
step:You could make this more point-free, or make it polymorphic just as above, but I won’t do that here. The point is that once you have
step, you can generate answers withrunState . last $ replicateM_ numIterations step, or given awhileMfunction,runState $ whileM (stoppingCondition :: State Solution Bool) step. Again, the user can decide how to stop it. Yourmovesandvaluefunctions would probably query the state withget :: State s s;applywould probably usemodify :: (s -> s) -> State s ()to tweak the state without needing to pull it back out. You can see the similarity with the structure from above in these types; and in fact, you can see that structure in the definition ofstep, as well. Each one says “string togetherapply,choose/value, andmoves“, which is the definition of your algorithm.The take-home message from both of these is that you want to avoid explicit loops/recursion, as you so rightly realized. If you think about this algorithm imperatively, then the
Statemonad seems like a natural structure, as it hides exactly those imperative features you were thinking of. However, it has downsides: for instance, everything has become monadic, and—worst of all—functions other thanapplyare able to change the saved solution. If you instead imagine this algorithm as producing a new result each time, you get the notion ofstep :: Solution -> Solution, and from there you can useiterateto get a well-behaved infinite list.