簡體   English   中英

努力理解“無法構造無限類型”錯誤

[英]Struggling to understand a “Cannot construct the infinite type” error

我正在嘗試解決 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)' 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)' 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)

您的foldSolution (length' xs)需要ta並返回a 因此,當您在tripleMap tripList xs (類型為([a], [a], [a]) )上對其進行三重映射時,您會得到一個類型為(a, a, a)的元組,而不是([a], [a], [a]) ,這就是你得到錯誤的原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM