gpt4 book ai didi

haskell - 读取实例导致解析错误

转载 作者:行者123 更新时间:2023-12-02 11:57:29 24 4
gpt4 key购买 nike

我想实现一个 read 实例,使我能够读取字符串(例如:“- - 8 - 3 -”)并构造一个包含这些值的列表。

data Value a = Nul | Val a

showsValue :: (Show a) => Value a -> ShowS
showsValue (Val x) = ("Value" ++) . shows x
showsValue (Nul) = ("Nothing 0" ++)

instance Show a => Show (Value a) where
showsPrec _ x = showsValue x

instance Read a => Read (Value a) where
readsPrec _ m = readsMatrix m

readsMatrix :: (Read a) => ReadS (Value a)
readsMatrix ('-':s) = [(Nul, rest) | (' ',rest) <- reads s]
readsMatrix s = [(Val x,rest)| (x,' ':rest) <- reads s]

执行此测试后:

read "- 8 - - 3" :: Value Int

我收到错误*** 异常:Prelude.read:无解析

我在这里做错了什么?

更新

readsMatrix ('-':s) = [(Nul, dropWhile isSpace s)]
readsMatrix s = [(Val x, dropWhile isSpace rest) | (x,rest) <- reads s]

最佳答案

更正值 a 的读取

首先,不用费心删除空格,这一切都可以通过 reads 处理得很好:

readsMatrix :: (Read a) => ReadS (Value a)
readsMatrix ('-':s) = [(Nul, dropWhile (==' ') s)]
readsMatrix s = [(Val x,rest)| (x,rest) <- reads s]

您的读取实例现在适合单个值:

*Main> read "4" :: Value Int
Value4
*Main> read "-" :: Value Int
Nothing 0

更正 [Value a] 的读取

但是您想要读取由空格分隔的列表,因此由于这是非标准行为,您需要编写一个自定义 readList::::ReadS [Value a]

instance Read a => Read (Value a) where
readsPrec _ m = readsMatrix m
readList s = [(map read.words $ s,"")]

那么现在

*Main> read "- 4 2 - 5" :: [Value Int]
[Nothing 0,Value4,Value2,Nothing 0,Value5]

但不幸的是,

*Main> read "- 4 2 \n- 5 4" :: [Value Int]
[Nothing 0,Value4,Value2,Nothing 0,Value5,Value4]

更糟糕的是,

*Main> read "- 4 2 \n- 5 4" :: [[Value Int]]
*** Exception: Prelude.read: no parse

读取矩阵

我认为没有直接的方法来解决这个问题,因为 Read 类中没有 readListOfLists,所以为什么不创建一个独立的函数

matrix :: Read a => String -> [[Value a]]
matrix = map read.lines

这样

*Main> matrix "3 4 -\n3 - 6\n4 5 -" :: [[Value Int]]
[[Value3,Value4,Nothing 0],[Value3,Nothing 0,Value6],[Value4,Value5,Nothing 0]]

显示不是我会选择的

我认为您的 ValueShow 实例有点误导(Nul 上面没有零,Val 未写为Value)。要么写

data Value a = Nul | Val a  deriving Show

使其看起来保持原样或定义它以匹配Read实例

instance Show a => Show (Value a) where
show Nul = "-"
show (Val a) = show a

关于haskell - 读取实例导致解析错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13553794/

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