Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 896
sudo97 Avatar asked Jun 30 '19 18:06

sudo97


People also ask

How do you check if a String can be parsed?

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.

How do I test type in Haskell?

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.

What is parser in Haskell?

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.

How do I check if a String has empty Haskell?

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.


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]
like image 73
Willem Van Onsem Avatar answered Oct 24 '22 19:10

Willem Van Onsem