我在寫一個遞歸函數mxAndC
。當我給它一個列表時,它應該返回一個元組。元組將具有給定列表的最大值作爲其第一個元素,第二個元素將是該元素在列表中出現的次數。作業不允許我創建輔助函數。我期待下面的輸出:返回列表的最大值和出現次數的函數
mxAdC "bananas" = (s,1)
mxAdC "banana" =(n,2)
mxAdC [mod x 4 | x <- [1..50]] -> (3,12)
我做了以下內容:
mxAdC = go 0
where go count (x:xs)
| count /= 0 = (mx, count)
| null ((x:xs)) = error "The list is empty"
| x == mx = go (count+1) xs
where mx = maximum (x:xs)
而且我得到錯誤:
* Ambiguous type variable `a0' arising from a use of `go'
prevents the constraint `(Ord a0)' from being solved.
Relevant bindings include
mxAdC :: [a0] -> (a0, Integer) (bound at hw06.hs:24:1)
Probable fix: use a type annotation to specify what `a0' should be.
These potential instances exist:
instance (Ord a, Ord b) => Ord (Either a b)
-- Defined in `Data.Either'
instance Ord Ordering -- Defined in `GHC.Classes'
instance Ord Integer
-- Defined in `integer-gmp-1.0.0.1:GHC.Integer.Type'
...plus 23 others
...plus 38 instances involving out-of-scope types
(use -fprint-potential-instances to see them all)
* In the expression: go 0
In an equation for `mxAdC':
mxAdC
= go 0
where
go count (x : xs)
| count /= 0 = (mx, count)
| null ((x : xs)) = error "The list is empty"
| x == mx = go (count + 1) xs
where
mx = maximum (x : xs)
我在Haskell很新。那裏的任何善意的專家都喜歡伸出手幫助這個新手?
你應該爲你的函數添加類型簽名。 – duplode
[Haskell:這個代碼中的錯誤來源是什麼「Ambiguous type variable ... \' Integral t'...''RealFrac t'...」)(http://stackoverflow.com/questions/3642277/haskell-what-is-the-source-of-error-ambiguous-type-variable-integral-t) – duplode
@duplode:我認爲這不是真的重複。另一個問題有一個_contradicting_類型,這個原則上是可行的,但有一個單態限制問題。相同的錯誤消息,但是完全不同的底層問題。 – leftaroundabout