Monad signaling converter missing solution list with `Nothing`

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 nas 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 Nothingif no solution is found. This is not what I got. The result that I got, most likely, will be the result of how it mzerois 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
[]
+4
1

, Maybe , , . , .

testList :: ListT Maybe a -> ListT Maybe a
testList (ListT (Just [])) = ListT Nothing
testList x = x

-, , NonEmpty ( , , ListT, , ). NonEmptyT.

newtype NonEmptyT m a = NonEmptyT { unNonEmptyT :: m (NonEmpty a) }

-- Instance implementations omitted for brevity

instance Functor m => Functor (NonEmptyT m) where
    ...

instance Applicative m => Applicative (NonEmptyT m) where
    ...

instance Monad m => Monad (NonEmptyT m) where
    ...

instance MonadTrans NonEmptyT where
    ...

testList' :: [a] -> NonEmptyT Maybe a
testList' [] = NonEmptyT Nothing
testList' (x:xs) = NonEmptyT $ Just (x :| xs)

NonEmptyT Maybe. , , , (ListT (Just [])), . NonEmptyT Nothing, NonEmptyT (Just someNonemptyList), NonEmptyT (Just []) typecheck.

, , , , , , .

.


(: , GHC , GeneralizedNewtypeDeriving, DeriveFunctor , . - , , .)

+1

Source: https://habr.com/ru/post/1692812/


All Articles