Greetings to a friend of the Haskellers.
This is a toy version of the problem with a large restriction of restrictions. I am working at the moment.
The code below uses a monad list transformer to represent a given positive integer n
as the sum of small even integers in different paths.
import Control.Monad.Trans.List
import Control.Monad
sumToN' :: Int -> ListT Maybe [Int]
sumToN' n
| n == 0 = pure []
| otherwise =
do
x <- ListT $ Just [1..4]
guard $ x <= n
guard $ even x
fmap (x:) $ sumToN' $ n - x
After loading into GHCi, the function works as expected.
λ> sumToN' 8
ListT (Just [[2,2,2,2],[2,2,4],[2,4,2],[4,2,2],[4,4]])
λ> sumToN' 7
ListT (Just [])
However, I was hoping to add some style to my code by specifying a function that will return ListT Nothing
if no solution is found. This is not what I got. The result that I got, most likely, will be the result of how it mzero
is determined for ListT
.
λ> mzero :: ListT Maybe [Int]
ListT (Just [])
: Maybe
, Nothing
. ( . ,
- .)
, ,
[]
.
sumToN :: Int -> [[Int]]
sumToN 0 = [[]]
sumToN n = do
x <- [1..4]
guard $ x <= n
guard $ even x
map (x:) $ sumToN $ n - x
, .
λ> sumToN 8
[[2,2,2,2],[2,2,4],[2,4,2],[4,2,2],[4,4]]
λ> sumToN 7
[]