So I have my own data type in haskell defined like this:
data Token = Num Double | Op String
I want to make a function that converts a list of strings into a list of tokens. E.g.
toTokenList ["2","+","3"]
> [Num 2.0, Op "+", Num 3.0]
How would I go about doing this?
I have implemented a function that converts a type Double
into a Token
type and another one that converts a String
to a Token
type. Can these be used for toTokenList
or no?
I am new to Haskell relatively and if you need further clarification about the question please let me know in the comments.
Using the parseDouble() method Therefore, to know whether a particular string is parse-able to double or not, pass it to the parseDouble method and wrap this line with try-catch block. If an exception occurs this indicates that the given String is not pars able to double.
If you are using an interactive Haskell prompt (like GHCi) you can type :t <expression> and that will give you the type of an expression. e.g. or e.g.
Parser combinators are known to be simple to use without requiring external tools or too many concepts to learn. That is, they are ordinary Haskell constructors that can easily be combined and returned with other parsers because of their nature as functions.
A String in Haskell is a list of characters. So to match the empty String you need to match an empty list ( [] ). Your pattern (x:xs) will only match lists or String s with at least one element because it consists of one element ( x ) and the rest ( xs ), which could be empty or non-empty.
We can implement an algorithm that is optimistic, it first aims to parse it as a Double
, and in case that fails, we return an Op
for that string, like:
import Text.Read(readMaybe)
toTokenList :: [String] -> [Token]
toTokenList = map (\x -> maybe (Op x) Num (readMaybe x))
or point-free:
toTokenList :: [String] -> [Token]
toTokenList = map (flip maybe Num . Op <*> readMaybe)
We here make use of readMaybe :: Read a => String -> Maybe a
, and maybe :: b -> (a -> b) -> Maybe a -> b
to provide a fallback and post-process the value.
For example:
Prelude Data.Maybe Text.Read> toTokenList ["2","+","3"]
[Num 2.0,Op "+",Num 3.0]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With