简体   繁体   中英

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

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. Eg

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.

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]

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