【发布时间】:2020-06-18 22:30:48
【问题描述】:
我正在尝试解决 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 将三组数字列表作为其第二个参数。
在我的 REPL 中测试 tripList 时,我得到了想要的结果:
> tripList [1,0,-1,0,1]
([1,1],[0,0],[-1])
这是我的代码:
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)
【问题讨论】:
标签: haskell