你好哈斯凯勒人,
我从一个月开始学习 Haskell,我正在努力为个人数据类型创建自定义读取实例。
我遵循了这个和Learn Yourself a Haskell 中的相关章节,这是我的代码片段。
data Position = Position (Absc,Ordn) deriving (Show)
instance Read (Position) where
readsPrec _ input =
let absc = List.filter (/='(') $ takeWhile (/=',')
ordn = List.filter (/=')') $ tail (dropWhile (/=',') )
in (\str -> Position ( (read (absc str) :: Int)
, (read (ordn str) :: Int) ) ) input
type Absc = Int
type Ordn = Int
我的目标是解析输入"(1,3)"
以输出类似Position (1,3)
但是,我收到以下错误消息:
• Couldn't match expected type ‘[Char]’
with actual type ‘[Char] -> [Char]’
• Probable cause: ‘takeWhile’ is applied to too few arguments
In the second argument of ‘($)’, namely ‘takeWhile (/= ',')’
In the expression: filter (/= '(') $ takeWhile (/= ',')
In an equation for ‘absc’:
absc = filter (/= '(') $ takeWhile (/= ',')
ordn 函数也一样。
• Couldn't match expected type ‘[(Position, String)]’
with actual type ‘Position’
• In the expression:
(\ str
-> Position ((read (absc str) :: Int), (read (ordn str) :: Int)))
input
In the expression:
let
absc = filter (/= '(') $ takeWhile (/= ',')
ordn = filter (/= ')') $ tail (dropWhile (/= ','))
in
(\ str
-> Position ((read (absc str) :: Int), (read (ordn str) :: Int)))
input
In an equation for ‘readsPrec’:
readsPrec _ input
= let
absc = filter (/= '(') $ takeWhile (/= ',')
ordn = filter (/= ')') $ tail (dropWhile (/= ','))
in
(\ str
-> Position ((read (absc str) :: Int), (read (ordn str) :: Int)))
input
似乎我的let
声明没有将absc
and识别ordn
为函数(或者至少尝试直接应用它们,而我只想将它们定义为部分应用的函数,以便稍后在参数处应用它们str
)。我也可能弄乱了我的Position
值构造函数。
我对 Haskell 编码风格不熟悉,可能使用了一些我不完全理解的关键字和工具。你能提示我如何编写它以使其工作吗?
先感谢您。