gpt4 book ai didi

haskell - 如何将函数映射到列表并在满足条件时停止并告诉我它是停止还是到达末尾?

转载 作者:行者123 更新时间:2023-12-03 18:33:27 25 4
gpt4 key购买 nike

我想在列表上应用一个函数,但是如果在任何时候,函数返回的结果是某种类型的,那么我不想继续迭代其余的元素。
我知道我可以用这个功能实现这一点:

example p f ls = takeWhile p $ map f ls
问题是我想知道它是否到达列表的末尾,或者它是否没有这样做。
想到了这个函数,但是好像有点麻烦:
haltmap :: Eq a => (a -> Bool) -> (b -> a) -> [a] ->  [b] -> Either [a] [a]
haltmap _ _ acc [] = Right acc
haltmap p f acc (h:t)
| p output = Left acc
| otherwise = haltmap p f (acc ++ [output]) t
where output = f h
我使用 Left 和 Right 来知道它是否通过了整个列表。
我确信有更好的方法来做到这一点。

最佳答案

我会使用 span为了这。这就像 takeWhile 但它为您提供了一对列表的其余部分以及匹配的部分,如下所示:

> span (<3) [1,2,3,2,1]
([1,2],[3,2,1])
然后你可以检查余数是否为空:
haltmap :: (a -> Bool) -> (b -> a) -> [b] -> Either [a] [a]
haltmap p f xs = (if null rest then Right else Left) ys
where
(ys, rest) = span p (map f xs)

关于haskell - 如何将函数映射到列表并在满足条件时停止并告诉我它是停止还是到达末尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65741734/

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