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

Gid*_*pta 8 haskell

So I have my own data type in haskell defined like this:

data Token = Num Double | Op String
Run Code Online (Sandbox Code Playgroud)

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]
Run Code Online (Sandbox Code Playgroud)

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.

Thanks in advance!

Wil*_*sem 2

我们可以实现一个乐观的算法,它首先旨在将其解析为 a Double,如果失败,我们Op为该字符串返回 an ,例如:

import Text.Read(readMaybe)

toTokenList :: [String] -> [Token]
toTokenList = map (\x -> maybe (Op x) Num (readMaybe x))
Run Code Online (Sandbox Code Playgroud)

或无点:

toTokenList :: [String] -> [Token]
toTokenList = map (flip maybe Num . Op <*> readMaybe)
Run Code Online (Sandbox Code Playgroud)

我们在这里利用readMaybe :: Read a => String -> Maybe a, 并maybe :: b -> (a -> b) -> Maybe a -> b提供后备和后处理该值。

例如:

Prelude Data.Maybe Text.Read> toTokenList ["2","+","3"]
[Num 2.0,Op "+",Num 3.0]
Run Code Online (Sandbox Code Playgroud)