【发布时间】:2017-03-18 19:43:41
【问题描述】:
我正在编写一个递归函数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:我认为这并不是真正的重复。另一个问题有一个矛盾类型,这个问题原则上是合理的,但有一个单态限制问题。相同的错误消息,但根本问题完全不同。
-
@duplode 您提到的与我的问题重复的问题并没有真正解决我的问题,尽管它们有相同的错误消息。请重新阅读我的问题。谢谢。
-
@leftaroundabout 确实。关闭投票撤回,然后。
标签: haskell recursion functional-programming higher-order-functions