我需要创建一个包含两个参数的函数,一个 Int
和一个 [Int]
,它返回一个新的 [Int]
删除所有出现的第一个参数。
我可以通过列表理解和列表递归轻松创建该函数。但是,我使用这些参数来做到这一点:
deleteAll_list_comp :: Integer -> [Integer] -> [Integer]
deleteAll_list_rec :: (Integer -> Bool) -> [Integer] -> [Integer]
但是,对于我的作业,我所需的参数是
deleteAll_list_comp :: (Eq a) => a -> [a] -> [a]
deleteAll_list_rec :: (Eq a) => a -> [a] -> [a]
我不知道如何阅读这个语法。正如 Google 告诉我的,(Eq a)
只是向 Haskell 解释 a
是一种可比较的类型。但是,我不明白这一点,因为所有 Int 自然都是可比较的。我如何使用这些参数来解释和实现这些方法?我的意思是,开始时的参数到底是什么?
@groovy @pelotom
谢谢,这已经很清楚了。我现在明白了,它实际上只要求两个参数,而不是三个。但是,我仍然遇到此代码的问题。
deleteAll_list_rec :: (Eq a) => a -> [a] -> [a]
delete_list_rec toDelete [] = []
delete_list_rec toDelete (a:as) =
if(toDelete == a) then delete_list_rec toDelete as
else a:(delete_list_rec toDelete as)
这给了我一个“deleteAll_list_rec
的类型签名
缺少随附的绑定(bind)”,这对我来说毫无意义,因为我如何正确绑定(bind)需求,不是吗?根据我的小经验,(a:as)
在提取其中的第一个元素。为什么这会生成错误,但是
deleteAll_list_comp :: (Eq a) => a -> [a] -> [a]
deleteAll_list_comp toDelete ls = [x | x <- ls, toDelete==x]
不是吗?
<小时/>2/7/13 更新:对于所有将来可能遇到同样问题的人,我已经找到了一些有关 Haskell 的好信息,特别是我的问题,在此链接:http://learnyouahaskell.com/types-and-typeclasses
"Interesting. We see a new thing here, the => symbol. Everything before the => symbol is >called a class constraint. We can read the previous type declaration like this: the >equality function takes any two values that are of the same type and returns a Bool. The >type of those two values must be a member of the Eq class (this was the class constraint).
The Eq typeclass provides an interface for testing for equality. Any type where it makes >sense to test for equality between two values of that type should be a member of the Eq >class. All standard Haskell types except for IO (the type for dealing with input and >output) and functions are a part of the Eq typeclass."
最佳答案
考虑参数的一种方法可能是:
(Eq a) => a -> [a] -> [a]
(Eq a) => means any a's in the function parameters should be members of the
class Eq, which can be evaluated as equal or unequal.*
a -> [a] means the function will have two parameters: (1) an element of
type a, and (2) a list of elements of the same type a (we know that
type a in this case should be a member of class Eq, such as Num or
String).
-> [a] means the function will return a list of elements of the same
type a; and the assignment states that this returned list should
exclude any elements that equal the first function parameter,
toDelete.
(*根据 pelotom 的评论进行编辑)
关于haskell - 如何解释(等式a),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14700140/