How do i check if a string can be parsed to a certain type in Haskell?

Viewed 625

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.

1 Answers

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]
Related