So I have this calculator I’m building that accepts user variable inputs like “let a = 2” These variable are stored in a List of Tuples (Variable, value) I need help with getting the data from this list. My code so far
primary :: Parser Float
primary = do symbol "("
e <- expression
symbol ")"
return e
+++ do v <- identifier
let a = (find (==(head v)) vlist)
return a
I get an error because find returns a Maybe and I need it to return a Float or give the user an error message. How do I do this?
I’m not sure where
vlistcomes from. It should probably be part of the parser’s user state. For now, let’s assume it’s a top-level definition:I assume you’re using
Parsec. You can simplify your parser to:You have several options for how to deal with the error. Here, I have used the parser monad’s
failfunction. This will cause the parser to return aLeft parserError. Alternatively, you could substituteerrorforfail, which will result in an error that can only be handled in theIOmonad.Note: To add the
vlistas parser state, you need to define a new parser type with that state: