Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I compose ReadS and ReadP?

Tags:

haskell

I am trying to compose a parser with ReadP, and I wanted to use read to parse numbers. But I must be missing something because even the most trivial example misbehaves:

λ import Text.ParserCombinators.ReadP
λ (readP_to_S . readS_to_P $ (read :: ReadS Int)) "123" :: [(Int, String)]
*** Exception: Prelude.read: no parse

I even specified the types everywhere, but it just does not work. What am I doing wrong?

like image 612
Ignat Insarov Avatar asked Nov 18 '25 23:11

Ignat Insarov


1 Answers

You need to replace your use of read with reads:

> (readP_to_S . readS_to_P $ (reads :: ReadS Int)) "123" :: [(Int, String)]
                              ^^^^^
[(123,"")]

It's unfortunate that it typechecked with read, but it's because the type signature for read is so general. In fact, the parser read :: ReadS Int is trying to parse a list of tuples of integers and strings!!!

> (read :: ReadS Int) "[(1,\"hi\"),(2,\"bye\")]"
[(1,"hi"),(2,"bye")]

which is definitely not what you want.

like image 198
K. A. Buhr Avatar answered Nov 20 '25 19:11

K. A. Buhr



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!