我必须从文本文件(空格分隔)中读取数据结构,每行一个数据项.我的第一个尝试是
data Person = Person {name :: String, surname :: String, age :: Int, ... dozens of other fields} deriving (Show,...)
main = do
string <- readFile "filename.txt"
let people = readPeople string
do_something people
readPeople s = map (readPerson.words) (lines s)
readPerson row = Person (read(row!!0)) (read(row!!1)) (read(row!!2)) (read(row!!3)) ... (read(row!!dozens))
Run Code Online (Sandbox Code Playgroud)
这段代码有效,但代码readPerson很糟糕:我必须复制粘贴read(row!!n))数据结构中的所有字段!
所以,作为第二次尝试,我认为我可能会利用Person函数的Currying ,并在当时传递一个参数.
嗯,Hoogle肯定有东西,但我无法弄清楚签名的类型......没关系,它看起来很简单,我可以自己编写:
readPerson row = readFields Person row
readFields f [x] = (f x)
readFields f (x:xs) = readFields (f …Run Code Online (Sandbox Code Playgroud) 我想编写一个函数mapsucc,它生成列表中每个项的后继.很容易:
mapsucc xs = map succ xs
Run Code Online (Sandbox Code Playgroud)
工作得很好.我想我可以使用Currying来使这个定义更短:
mapsucc = map succ
Run Code Online (Sandbox Code Playgroud)
但我得到:
No instance for (Enum b0) arising from a use of ‘succ’
The type variable ‘b0’ is ambiguous
Relevant bindings include
mapsucc :: [b0] -> [b0] (bound at mapsucc.hs:1:1)
Note: there are several potential instances:
instance Enum Ordering -- Defined in ‘GHC.Enum’
instance Enum Integer -- Defined in ‘GHC.Enum’
instance Enum () -- Defined in ‘GHC.Enum’
...plus six others
In the first argument of ‘map’, namely ‘succ’
In …Run Code Online (Sandbox Code Playgroud) haskell ×2