无法摆脱这种类型的错误
Can't get rid of this type error
我正在尝试解决 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]
你进行了错误的模式匹配。由于 solve
必须接受大小正好为 4 的列表,模式匹配必须是这样的:
solve [_,r,_,a] = ...
可以脱糖为:
solve (_:r:_:a:[]) = ...
或进一步脱糖:
solve (_:(r:(_:(a:[])))) = ...
记住,:
左边是一个元素,右边是一个列表!
我正在尝试解决 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]
你进行了错误的模式匹配。由于 solve
必须接受大小正好为 4 的列表,模式匹配必须是这样的:
solve [_,r,_,a] = ...
可以脱糖为:
solve (_:r:_:a:[]) = ...
或进一步脱糖:
solve (_:(r:(_:(a:[])))) = ...
记住,:
左边是一个元素,右边是一个列表!