我正在尝试解决this problem。
这是我的代码:
import Data.List (nub)
main = interact $ unwords . map show . solve . map words . lines
solve :: [[String]] -> [Int]
solve (_:r:_:a) = map (rank . read) a
where records = nub $ map read r :: [Int]
rank n = (length $ takeWhile (> n) records) + 1
编译器抛出此错误:
* Couldn't match type `[Char]' with `Char'
Expected type: [String]
Actual type: [[String]]
* In the second argument of `map', namely `a'
In the expression: map (rank . read) a
In an equation for `solve':
solve (_ : r : _ : a)
= map (rank . read) a
where
records = nub $ map read r :: [Int]
rank n = (length $ takeWhile (> n) records) + 1
|
6 | solve (_:r:_:a) = map (rank . read) a
|
我不明白问题是什么。当我在GHCi中将它们逐行拼凑在一起时,它会起作用:
GHCi> import Data.List (nub)
GHCi> records = nub $ map read ["100", "100", "50", "40", "40", "20", "10"] :: [Int]
GHCi> rank n = (length $ takeWhile (> n) records) + 1
GHCi> a = ["5", "25", "50", "120"]
GHCi> map (rank . read) a
[6,4,2,1]
答案 0 :(得分:2)
您进行了错误的模式匹配。由于solve
必须接受大小为4的列表,因此模式匹配必须像这样:
solve [_,r,_,a] = ...
哪些可以放心使用:
solve (_:r:_:a:[]) = ...
甚至进一步贬低:
solve (_:(r:(_:(a:[])))) = ...
请记住,:
在左边带有一个元素,在右边带有一个列表!