Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Maybe and Writer together

Here is my egg packing factory:

type Eggs = Int
data Carton = Carton Eggs deriving Show

add :: Eggs -> Carton -> Maybe Carton
add e (Carton c)
    | c + e <= 12 = Just (Carton $ c + e)
    | otherwise = Nothing

main = do
    print $ pure(Carton 2) >>= add 4 >>= add 4 >>= add 3

Seems to work well, I can nicely chain add functions.

But I want to record a log of how many eggs were added at every step. So I do this:

import Control.Monad.Writer

type Eggs = Int
data Carton = Carton Eggs deriving Show

add :: Eggs -> Carton -> Writer [String] (Maybe Carton)
add e (Carton c)
    | c + e <= 12 = do
        tell ["adding " ++ show e]
        return (Just (Carton $ c + e))
    | otherwise = do
        tell ["cannot add " ++ show e]
        return Nothing

main = do
    let c = add 4 $ Carton 2
    print $ fst $ runWriter c
    mapM_ putStrLn $ snd $ runWriter c

This gives me what I want: I can see the resulting carton and the record for 4 eggs being added.

But I seem to have lost the ability to chain add functions like I did before:

let c = pure(Carton 2) >>= add 4 -- works
let c = pure(Carton 2) >>= add 4 >>= add 2 -- does not work

How can I chain my new writer-enabled add functions? Is there a better way of doing this?

like image 804
zoran119 Avatar asked Jul 05 '16 02:07

zoran119


People also ask

Is it correct to say maybe?

Maybe /ˈmeɪbi/ is an adverb and it means the same as perhaps. It is written as one word: Maybe no one will come to the party. Not: May be no one will come to the party.

Can you use maybe and will together?

So saying, “Maybe it will rain today” is totally acceptable. Another example that uses both “maybe” and “will” is “Maybe my friends will visit.” Keep in mind that using the modal “may” or “might” is a more common way to express these kinds of possibilities.

Is it grammatically correct to start a sentence with maybe?

Maybe is commonly used to describe the probability of an action happening or not happening—maybe means it might or it might not happen. In other cases, it just means “perhaps.” These senses of maybe can be used anywhere in a sentence—the beginning, middle, or end. Maybe I'll join you after all.

Where do you put maybe in a sentence?

Maybe can be used in the following ways: as a sentence adverb, making a comment on the whole sentence or clause: Maybe I'll come too. as an ordinary adverb (before a number): There were maybe 15 people there. Maybe it will snow tonight and school will be cancelled.


1 Answers

Just compose add with MaybeT:

import Control.Trans.Monad.Maybe

test = pure (Carton 2) >>= MaybeT . add 3
                       >>= MaybeT . add 4
                       >>= MaybeT . add 5

runTest = do
  print $ fst $ runWriter (runMaybeT test)

Full example at: http://lpaste.net/169070

like image 74
ErikR Avatar answered Oct 15 '22 19:10

ErikR