我是haskell的新手。有人可以解释我怎么能解释这行代码在Haskell:了解haskell代码
filter (\(_, (varible1, _)) -> variable1 `notElem` [something1, something2])
我是haskell的新手。有人可以解释我怎么能解释这行代码在Haskell:了解haskell代码
filter (\(_, (varible1, _)) -> variable1 `notElem` [something1, something2])
-- Filter a list...
filter
-- ...of nested tuples where the first element of the second element of the tuple...
(\(_, (variable1, _)) ->
-- ...is not an element of [something1, something2]
variable1 `notElem` [something1, something2])
(_, (varible1, _))
解构嵌套元组和名称的要素之一。查看解构以了解那里正在发生的事情。
那么它是否会返回“嵌套“斑点? –
是的,它会接受一个类似'[(1,(2,3)),(9,(8,7))]''的列表,并返回一个相同类型的列表(可能与一些元素被删除),老实说,这里的嵌套元组会让事情变得杂乱无章,我可能会有'map'除非你实际需要嵌套元组以供稍后使用,否则先删除嵌套。 – Carcigenicate
非常感谢您的解答:D –
让我们从头开始。
\p -> e
是拉姆达抽象(匿名函数),其中p
是一个模式和e
是可以使用出现在p
变量的表达式。
(_, (variable1, _))
是从构造(,)
,它构造对构造的模式。以下是一些配对:
(1, 2)
("Hello", "world!")
(1, (2, 3))
下面是一些与lambda抽象中使用的对匹配的模式。
\(x, y) -> x
\(x,(y,z)) -> y
第二图案相匹配的一对像(1, (2, 3))
,并给出了第二元件的第一元件。在这种情况下,它会给2
。它的形状就像你问题中的模式,但你的模式中的_
怎么样?
_
是一个有效的变量名(变量可以以下划线或小写字母开头)。它被用来表示“我们不使用的变量”。模式(_, (y, _))
与模式(x, (y, z))
类似,只是名称唯一的变量是y
。通常情况下,您不允许在模式中重复使用变量名称。例如,(x,x)
处于无效模式。尽管您可以重用_
,但Haskell知道您打算抛弃该值。现在
我们可以理解表达
\(_, (variable1, _)) -> variable1
它是(a, (b, c)) -> b
型,这需要对其第二元件是本身的一对,并给出了第二元件的第一元件的功能。
现在,我们需要了解
variable1 `notElem` [something1, something2]
要理解这个表达式,我们需要知道什么是反引号做。在反引号中围绕一个标识符将其变成一个中缀运算符。中缀操作员通常拼写符号,如x + y
和xs ++ ys
。反引号让我们将普通标识符(如notElem
)转换为中缀运算符。这意味着,上面的表达式是相同的
notElem variable1 [something1, something2]
notElem
是取一个项目,相同类型的项目的列表,并给出True
的函数,如果该项目不出现在列表和False
除此以外。这与elem
成员资格测试相反。最后,filter
。 filter p xs
是以谓词p
(即,返回Bool
的函数)并使用它来过滤列表xs
的函数。 filter
给出了一个新的列表,其中包含元素(称为它们x
),如果p x
为真。这将筛选xs
的列表,并给出一个新列表,其元素是那些谓词为真的列表。例如,
> filter even [1,2,3,4]
[2,4]
因此,我们有
filter -- filter a list
(\(_, (variable1, _)) -- by matching on the first element
-- of the second element of a pair
-- and calling it 'variable1'
-> variable1 `notElem` [something1, something2])
-- and giving `True` if the element
-- is neither 'something1' nor 'something2'
这给出了一个函数,该函数对第二个元素是一对的列表,它过滤到第二个元素是对的列表其第一个元素既不是something1
也不是something2
。与
f = filter (\(_, (varible1, _)) -> variable1 `notElem` [something1, something2])
> f [(1,(something1,2)), (1,(something3,3))]
[(1,(something3,3))]
感谢您的详细解释:D –
,你有哪一部分的问题:
我们可以应用它,称它下面
f
? – Carcigenicate其实我不明白'过滤器(\(_,(varible1,_))'还有代码 –
中的流程我想你必须仔细看看括号。'(\(_,(varible1,_ )) - > variable1 \'notElem \'[something1,something2])'是一个单一的lambda表达式。 –