Haskell Is there a function for creating every variation of applying a function to a list

3 haskell functional-programming function list

I want to create a list of variations of applying a function to every element of a list. Here is a quick example of what I mean.

applyVar f [a, b, c]
>> [[(f a), b, c], [a, (f b), c], [a, b, (f c)]]
Run Code Online (Sandbox Code Playgroud)

Essentially It applies a function to each element of a list individually and stores each possible application in an array.

I'm not too sure how to approach a problem like this without using indexes as I have heard they are not very efficient. This is assuming that the function f returns the same type as the input list.

Is there a pre-existing function to get this behavior? If not what would that function be?

Jos*_*ica 7

要查看是否存在预先存在的函数,首先要弄清楚它的类型。在这种情况下,它是(a -> a) -> [a] -> [[a]]. 在 Hoogle 上搜索该类型只会返回少数匹配项,并且通过检查,它们都不会满足您的要求。

要自己编写它,请注意它对列表进行操作,弄清楚如何在列表上编写函数的最佳方法是归纳定义它。这意味着您需要构建两种情况:一种用于空列表,另一种用于假设您已经知道其尾部答案的非空列表:

applyVar f [] = _
applyVar f (x:xs) = _ -- use `applyVar f xs` somehow
Run Code Online (Sandbox Code Playgroud)

现在我们只需要填写两个空格。对于 nil 情况,这很容易。对于 cons 的情况,请注意第一个子列表以 开头f a,其余的都以 开头a。然后,请注意其余的尾巴看起来非常像尾巴的答案。从那里,模式应该变得清晰。

applyVar f [] = []
applyVar f (x:xs) = (f x:xs):map (x:) (applyVar f xs)
Run Code Online (Sandbox Code Playgroud)

这是它的快速演示/测试:

Prelude> applyVar (+10) [1,2,3]
[[11,2,3],[1,12,3],[1,2,13]]
Run Code Online (Sandbox Code Playgroud)

  • 非常感谢您的帮助,不仅提供解决方案,还提供解决此类问题的建议。 (2认同)