I have the following function:
parse :: String -> Maybe Token
And I am trying to implement the following function:
maketokenlist :: String -> Maybe [Token]
The function returns Nothing if there is a token that was not able to be parsed (i.e. parse returns Nothing if the token is not an integer or an arithmetic operator), otherwise it returns a list of Tokens.
As Maybe is an instance of the Monad type class, I have the following approach:
maketokenlist str = return (words str) >>= parse
I convert the string into a list of individual tokens (e.g. "2 3 +" becomes ["2","3","+"] , and then map the parse function over each string in the list.
Since the Monad instance for lists is defined as:
instance Monad [] where
return x = [x]
xs >>= f = concat (map f xs)
fail _ = []
However, say that I had the list of strings [2, 3, "+", "a"] and after mapping parse over each element using >>= I get [Just 2, Just 3, Just (+), Nothing], as "a" cannot be parsed. Is there a way to make the function maketokenlist return Nothing using just the >>= operator? Any insights are appreciated.
[2, 3, "+", "a"], This is neither a list, nor any construct that makes any sense in Haskell. A list must be made of a single type like so,[a]. So you could have[2,3]or["+","a"]. Rethink the problem, and try again. - Michael Litchardreturnwraps its argument in a monad, and>>=immediately unwraps it. Soreturn (words str) >>= parseis equivalent toparse (words str). Is there a reason you need to use>>=, instead of, say,maketokenlist str = map parse (words str)? - DarthFennec