Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List comprehension and converting string to object

I have a string, like 2.7+i*3.4. I want to parse this string and get Complex number object. I try to do this:

newtype MyComplexNumber = MyComplexNumber (Complex Float)

myReadsCmplx s = [(MyComplexNumber (a :+ b)) |
                               (a, '+':r1) <- reads s :: [(Float, String)],
                               (i, '*':r2) <- reads r1 :: [(String, String)],
                               (b, r3) <- reads r2 :: [(Float, String)]]

But I have empty list:

*Main Data.Complex> myReadsCmplx "2.7+i*3.4"
[]
*Main Data.Complex>
like image 454
David Avatar asked Dec 04 '25 12:12

David


1 Answers

You seem to be using reads as though it were a full monadic parser. It's not. It comes up with a match or none, and if the match it finds does not match your pattern, you get nada. You will be much better off using something like parsec, attoparsec, or even something super-simple like regex-applicative.

like image 71
dfeuer Avatar answered Dec 06 '25 05:12

dfeuer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!