gpt4 book ai didi

haskell - 我可以编写 ReadS 和 ReadP 吗?

转载 作者:行者123 更新时间:2023-12-05 03:00:12 24 4
gpt4 key购买 nike

我正在尝试用 ReadP 编写一个解析器,我想用 read 来解析数字。但我一定遗漏了一些东西,因为即使是最微不足道的例子也会出现错误:

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

我什至在各处都指定了类型,但它就是行不通。我做错了什么?

最佳答案

你需要用 reads 替换你对 read 的使用:

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

不幸的是,它使用read 进行了类型检查,但这是因为read 的类型签名太通用了。事实上,解析器 read::ReadS Int 正在尝试解析整数和字符串的元组列表!!!

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

这绝对不是你想要的。

关于haskell - 我可以编写 ReadS 和 ReadP 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57032938/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com