Dus*_*nny 0 printing string haskell list count
我有这个代码,我试图创建以计算记录数量并打印它们,我似乎无法使它工作我不断得到函数reportReg的错误应用于一个参数但其类型[String]没有.
report :: [[String]] -> String -> [String]
report (x:xs) typ = do
case typ of
"registrations" -> reportReg (map head xs)
"completions" -> reportReg (map head xs)
reportReg :: [String]
reportReg [x] = do
print x
print 1
reportReg (x:xs) = do
let count = instances x (x:xs)
print x
print count
let newlist = filter (==x) (x:xs)
reportReg newlist
instances::String->[String]->Int
instances x [] = 0
instances x (y:ys)
| x==y = 1+(instances x ys)
| otherwise = instances x ys
Run Code Online (Sandbox Code Playgroud)
另外,有更简单的方法吗?
问题:
您已经给出reportReg了一种字符串列表:
reportReg :: [String]
Run Code Online (Sandbox Code Playgroud)
这只是一个值,或0参数的函数.这解释了你得到的错误 - 试图给它一个参数,但它没有.
解决方案:
看起来您想要执行IO操作reportReg,因此您应该更改类型注释:
reportReg :: [String] -> IO ()
Run Code Online (Sandbox Code Playgroud)- 或 -
问题:
report回归类型错了.它必须与之相同reportReg.但是reportReg :: String -> IO (),而report :: [[String]] -> String -> [String]!
几种可能的解决方案:
reportReg,以便其类型为[String] -> [String].我强烈建议这样做 - 任何语言的IO总是很痛苦,但Haskell的酷炫之处在于它会让你感受到痛苦 - 从而激励你尽可能地避免IO!report为[[String]] -> String -> IO ()懒人的解决方案:
我将您的代码复制到一个文本文件中,删除了注释(不做任何其他更改),并将其加载到ghci:
Prelude> :load typef.hs
[1 of 1] Compiling Main ( typef.hs, interpreted )
Ok, modules loaded: Main.
*Main> :t report
report :: (Eq a, Show a) => [[a]] -> [Char] -> IO ()
*Main> :t reportReg
reportReg :: (Eq a, Show a) => [a] -> IO ()
*Main> :t instances
instances :: (Num t, Eq a) => a -> [a] -> t
Run Code Online (Sandbox Code Playgroud)
它的工作原理--Haskell推断出类型! 但它可能不会做你想要的.