英文:
Take first elements of 'xs' that are equal to 'a' without using takeWhile
问题
我想写一个函数 f :: a -> [a] -> [a],使得 f a xs 是一个包含与 a 相等的 xs 的第一个元素的列表,如果 xs 不以 a 开头,则列表为空。具体的例子将更清晰:
f 3 [3, 3, 2, 1, 3] = [3, 3]
f 3 [1, 3, 3, 2, 1, 3] = []
f 3 [1, 2, 5] = []
f "a" "aaaFS" = "aaa"
f "a" "elephant" = ""
我的问题是当找到一个值 x != a 时如何使递归 停止。这让我觉得递归本身可能不是解决这个问题的最佳方法。
换句话说,虽然很容易写一个从 xs 中获取所有 a 的函数,例如 f' 1 [1, 1, 2, 2, 1] = [1, 1, 1],但我不知道如何写一个仅获取 xs 中最初的 a 的函数;也就是说,一个 f 使得 f 1 [1, 1, 2, 2, 1] = [1, 1]。
英文:
I want to write a function f :: a -> [a] -> [a] such that f a xs is a list containing the first elements of xs that are equal to a, such that if xs does not start with a the list is empty. Specific cases will make this clearer:
f 3 [3, 3, 2, 1, 3] = [3, 3]
f 3 [1, 3, 3, 2, 1, 3] = []
f 3 [1, 2, 5] = []
f "a" "aaaFS" = "aaa"
f "a" "elephant" = ""
My issue is with making the recursion stop when a value x != a is found. Which makes me think recursion itself might not be the best way to approach this.
In other words, while it is easy to write a function that takes all a's from xs, such that f' 1 [1, 1, 2, 2, 1] = [1, 1, 1], I don't know how to write a function that takes only the initial a's from xs; this is, an f such that f 1 [1, 1, 2, 2, 1] = [1, 1].
答案1
得分: 1
您可以在这里使用递归。实际上,与许多列表处理一样,您可以使用:
<pre><code>f :: Eq a => a -> [a] -> [a]
f y = go
    where go [] = ...
          go (x:xs) = ...</code></pre>
对于类似过滤的函数,代码如下:
<pre><code>filter' :: Eq a => a -> [a] -> [a]
filter' y = go
    where go [] = []
          go (x:xs) | x == y = x : go xs
                    | otherwise = go xs</code></pre>
在这里,如果找到一个不相等的元素,您将需要阻止递归。我将这留给您作为练习。
英文:
You can use recursion here. Indeed, as with a lot of list processing, you can work with:
<pre><code>f :: Eq a => a -> [a] -> [a]
f y = go
where go [] = …
go (x:xs) = …</code></pre>
For the filter-like function, this looks like:
<pre><code>filter' :: Eq a => a -> [a] -> [a]
filter' y = go
where go [] = []
go (x:xs) | x == y = x : go xs
| otherwise = go xs</code></pre>
You will here have to prevent recursing if we found an element that is not equal. I leave this as an exercise.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论