Euler 43 - is there a monad to help write this list comprehension?

后端 未结 3 1779
遇见更好的自我
遇见更好的自我 2020-11-29 11:54

Here is a way to solve Euler problem 43 (please let me know if this doesn\'t give the correct answer). Is there a monad or some other syntatic sugar which could assist with

3条回答
  •  时光说笑
    2020-11-29 12:22

    The UniqueSel monad suggested by Louis Wasserman is exactly StateT [Integer] [] (I'm using Integer everywhere for simplicity).

    The state keeps the available digits and every computation is nondeterministic - from a given state we can select different digits to continue with. Now the choose function can be implemented as

    import Control.Monad
    import Control.Monad.State
    import Control.Monad.Trans
    import Data.List
    
    choose :: PanM Integer
    choose = do
        xs <- get
        x <- lift xs -- pick one of `xs`
        let xs' = x `delete` xs
        put xs'
        return x
    

    And then the monad is run by evalStateT as

    main = do
             let nums = evalStateT pandigitals [0..9]
             -- ...
    

提交回复
热议问题