等式=> Haskell中的功能 [英] Eq => function in Haskell
问题描述
我试图弄清楚如何用Haskell中的Eq函数编写此函数.
I am trying to figure out how to write this function with the Eq function in Haskell.
我要实现的一个简单功能是:
An easy function that I am trying to implement is:
f :: Eq a => [a] -> [[a]]
其中f将在单独的子列表下收集每个重复的连续元素,例如:
Where f will gather each repeated consecutive elements under separate sub-lists, For example:
f [3] = [[3]]
f [1,1,1,3,2,2,1,1,1,1] = [[1,1,1],[3],[2,2],[1,1,1,1]]
我考虑过此功能:
f :: Eq a => [a] -> [[a]]
f [] = []
f (x:[]) = [[x]]
f (x:x':xs) = if x == x' then [[x, x']] ++ (f (xs))
else [[x]] ++ (bundler (xs))
它似乎不能很好地工作,因为当它到达最后一个元素时,它想将其与连续的元素进行比较,而后者显然是不存在的.
It seems to not work well since when it arrives to the last element, it wants to compare it to its consecutive, which clearly does not exist.
此外,我觉得我对Eq =>函数不使用任何东西.
Moreover, I feel like I do not use anything with the Eq => function.
我想收到一个答案,该答案将说明如何在我的情况下正确使用Eq.
I would like to receive an answer that will show how to use Eq properly in my case.
谢谢.
推荐答案
您的类型中出现的Eq
类型类是一个红色鲱鱼:它与您报告的错误无关.发生此错误的原因是,您已定义了当列表为空(f [] =
)且列表中至少包含两个元素(f (x:x':xs) =
)时函数的行为方式,但定义了列表中仅包含一个元素时函数的行为.解决方案是添加一个开始的案例*
The presence of the Eq
typeclass in your type is a red herring: it is not related to the error you report. The error you report happens because you have defined how the function should behave when the list is empty (f [] =
) and when the list has at least two elements (f (x:x':xs) =
), but not when the list has exactly one element. The solution will be to add a case that begins*
f [x] = ????
并决定如何处理一个元素列表.或者找到其他方式编写处理所有情况的函数.
and decide how to deal with one-element lists. Or to find some other way to write the function that deals with all of its cases.
*请注意,f [x]
与f (x:[])
是同一件事.
* Note that f [x]
is the same thing as f (x:[])
.
这篇关于等式=> Haskell中的功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!