我正在尝试解决 HackerRank 问题,但遇到了一个我无法弄清楚的错误。问题出在solve1函数上。确切的错误是:cannot construct the infinite type a ~ t0 a. Expected type ([t0 a], [t0 a], [t0 a]) Actual type ([a], [a], [a]). In the second argument of `tripleMap`, namely '(tripList xs)'。
我一直看着这些类型,它们在我眼中继续显得正确。tripList获取数字列表并返回数字列表的三元组。tripleMap将一组数字列表作为其第二个参数。
在tripList我的 REPL 中进行测试时,我得到了想要的结果:
> tripList [1,0,-1,0,1]
([1,1],[0,0],[-1])
Run Code Online (Sandbox Code Playgroud)
这是我的代码:
length' :: (Foldable t, Num b, Fractional b, Ord b) => t a -> b
length' = foldr (\_ acc -> 1 + acc) 0
tripList :: (Num a, Ord a) => [a] -> ([a], [a], [a])
tripList xs =
( filter (>0) xs
, filter (==0) xs
, filter (<0) xs )
foldSolution :: (Foldable t, Num a, Ord a, Fractional a)
=> a -> t a -> a
foldSolution n = foldr (\x y -> x/n + y/n) 0
tripleMap :: (a -> b) -> ([a], [a], [a]) -> ([b], [b], [b])
tripleMap f (a, b, c) = (map f a, map f b, map f c)
solve1 :: (Num a, Ord a) => [a] -> ([a], [a], [a])
solve1 xs = tripleMap (foldSolution (length' xs)) (tripList xs)
Run Code Online (Sandbox Code Playgroud)
你foldSolution (length' xs)需要t a和回报a。所以,当你打开tripleMap它tripList xs(它有 type ([a], [a], [a]))时,你会得到一个 type 的元组(a, a, a), not ([a], [a], [a]),这就是你得到错误的原因。