简体   繁体   中英

Haskell monads and the do statement

I'm new to monads and its use and the following structure using the do-statement had me quite confused:

pairs xs ys = do x <- xs
                 y <- ys
                 return (x, y)

I was told this should return all possible pairs of x and y, which I do not understand because I was earlier taught that the following code:

eval (Val n) = Just n
eval (Div x y) = do n <- eval x
                    m <- eval y
                    safediv n m

means: execute eval x , then keep its result if not equal to Nothing (otherwise return Nothing) as n , then the same for eval y , and then if both are not Nothing it will proceed to the final function safediv that combines both results (and otherwise return Nothing too).

However the 1st use of the do-statement in the function pairs works totally different?

If someone could help me out on this and explain what's the actually proper functionality of the do-statement and its structure, it'd be much appreciated!

Best regards, Skyfe.

The do construct works in any monad, and there you are using it in two different monads.

In the first case,

pairs xs ys = do x <- xs
                 y <- ys
                 return (x, y)

you are working in the list monad, ie [] . You can see that because you use x <- xs and xs is of type [something] .

In the second case

eval (Val n) = Just n
eval (Div x y) = do n <- eval x
                    m <- eval y
                    safediv n m

you are working in the Maybe monad. Indeed, you use y <- eval x and eval returns Maybe something .

Each monad defines its own rules about what <- should mean. In the list monad, it roughly means "consider all possible elements", in the Maybe one "take the x in Just x , and fail otherwise".

Technically, the <- construct within a do is desugared into a call to the >>= operator, which every monad defines independently.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM