【问题标题】:Struggling to understand a "Cannot construct the infinite type" error努力理解“无法构造无限类型”错误
【发布时间】: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


    【解决方案1】:

    您的foldSolution (length' xs) 接受t a 并返回a。所以,当你在tripList xs(类型为([a], [a], [a]))上tripleMap它时,你会得到一个(a, a, a)类型的元组,而不是([a], [a], [a]),这就是你得到错误的原因。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-30
      相关资源
      最近更新 更多