[英]Haskell Programming Assignment, “Couldn't match expected type ‘Int’ with actual type ‘[a0] -> Int’ ”and a few more Errors
[英]Haskell Couldn't match type ‘String -> [Int]’ with ‘[a0]’
我想创建一个计算列表中所有元素的出现并返回最大序列的程序。 我的输入部分有问题。
输入包含几个测试用例。 每个测试用例都从包含两个整数n和q(1≤n,q≤100000)的一行开始。 下一行包含n个整数a1,...,an(-100000≤ai≤100000
我希望readNQ获得n和q作为[int],然后传递给readArray,它将读取n个元素并分配给[int],如下所示
module Main where
import Text.Printf
import Data.List
main :: IO()
main = interact (showResults . maxSeqLength . readArray. readNQ)
readNQ :: String -> [Int]
readNQ = take 2 . (map read) . words
readArray :: [Int] -> String -> [Int]
readArray (n:xs) = take n . (map read) . words
showResults :: Int -> String
showResults x = printf "\n %d" x
maxSeqLength :: Eq a => [a] -> Int
maxSeqLength [] = 0
maxSeqLength xs = (maximum . map length . group) xs
但是,有一个错误。
quent.hs:13:47:错误:
• Couldn't match type ‘String -> [Int]’ with ‘[a0]’
Expected type: String -> [a0]
Actual type: String -> String -> [Int]
• Probable cause: ‘(.)’ is applied to too few arguments
In the second argument of ‘(.)’, namely ‘readArray . readNQ’
In the second argument of ‘(.)’, namely
‘maxSeqLength . readArray . readNQ’
In the first argument of ‘interact’, namely
‘(showResults . maxSeqLength . readArray . readNQ)’
readNQ和readArray的类型有什么问题?
readArray :: [Int] -> String -> [Int]
这需要一个[Int]
并返回一个函数String -> [Int]
maxSeqLength :: Eq a => [a] -> Int
这接受列表[a]
并返回Int
。
由于函数String -> [Int]
不是列表[a]
,因此不能使用(.)
。
除了错误,还要注意
readNQ = take 2 . (map read) . words
从输入中读取前两个int,并丢弃其余的。 它消失了。 函数链中的下一个函数(... . fun . readNQ)
无法访问从第一个函数抛出的内容。
如果您想让下一个函数使用它,则需要对readNQ
进行重新readNQ
以便它返回一对([n1,n2], restOfTheInput)
。
代码可能会变得太复杂而无法以无点样式表示,但这没关系。 此外, interact
很快开始无法用于大型任务。
那是因为您在函数readArray :: [Int] -> String -> [Int]
有类型readArray :: [Int] -> String
如果您希望此表达式有效,则它应该具有readArray :: [Int] -> String
类型:
(showResults . maxSeqLength . readArray . readNQ)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.