gpt4 book ai didi

list - Haskell 中的 span 函数

转载 作者:行者123 更新时间:2023-12-02 15:17:42 24 4
gpt4 key购买 nike

我认为span函数Haskell是将谓词应用于列表,并返回一个元组,其中第一个元素是列表中满足该条件的元素谓词,第二个元素是列表的提醒。

当我输入以下内容时效果很好: span (<3) [1,2,4,5,6] 。它只是在 GHCI 中返回: ([1,2], [4,5,6]) .

但是,当我输入span (>3) [1,2,4,5,6]时,它返回 ([],[1,2,4,5,6]) 。但我认为它应该返回 ([4,5,6],[1,2]) 。所以我想知道其中的原因。

最佳答案

您对span的理解不完全正确,官方文档是这样说的:

span, applied to a predicate p and a list xs, returns a tuple where first element is longest prefix (possibly empty) of xs of elements that satisfy p and second element is the remainder of the list

(强调我的)。

因此,谓词从头开始应用于列表的每个元素。这意味着谓词

span (<3) [1,2,4,5,6]

满足前两个元素,结果为

([1,2], [4,5,6])

但在另一个例子中

span (>3) [1,2,4,5,6]

列表的第一个元素已经不满足谓词,因此返回的元组的第一个元素将是一个空列表。

关于list - Haskell 中的 span 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59343416/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com