简体   繁体   English

Haskell 在列表 n 上执行 function 次数

[英]Haskell perform function on list n number times

I am learning functional programming using Haskell.我正在使用 Haskell 学习函数式编程。 I am trying to create a function that takes a function f , and executes the function on some input x , n number of times.我正在尝试创建一个 function ,它采用 function f ,并在某些输入x上执行n次。

(a -> a) -> a -> Int -> [a]
repeat f x n

So, the output list is like this:所以,output 列表是这样的:

[x, f(x), f(f(x)), ..., f^n(x)]

So far I have been able to come up with a function that I believe does this, but I don't know how to constrain it so it only performs n number of times:到目前为止,我已经能够想出一个 function 我相信这样做,但我不知道如何约束它,所以它只执行 n 次:

fn f a = (f a) : (fn f (f a))

Could someone lend a hand?有人可以帮忙吗? Thanks!谢谢!

You just need to specify two separate cases: one where recursion happens and the list continues, and another where recursion does not happen, and there needs to be some way to decide between the cases.您只需要指定两种不同的情况:一种情况下发生递归并且列表继续,另一种情况下不发生递归,并且需要某种方式来决定这些情况。 The third parameter n looks like just the right thing for that:第三个参数n看起来恰到好处:

fn f a 0 = []
fn f a n = f a : fn f (f a) (n-1)

I'm here to give another way (just for fun).我来这里是为了提供另一种方式(只是为了好玩)。

There is a very similar function: scanl:: (b -> a -> b) -> b -> [a] -> [b] in the library, it performs:库中有一个非常相似的 function: scanl scanl:: (b -> a -> b) -> b -> [a] -> [b] ,它执行:

scanl f z [x1, x2, ...] == [z, z `f` x1, (z `f` x1) `f` x2, ...]

which is quite similar to what you want to do.这与您想要做的非常相似。 So we can write:所以我们可以写:

fn :: (a -> a) -> a -> Int -> [a]
fn f a n = scanl (\x _ -> f x) a (replicate n ())

-- or you can write:
-- fn f a n = scanl (const . f) a (replicate n ())

In (\x _ -> fx) we discard the second parameter (which is the () ).(\x _ -> fx)中,我们丢弃了第二个参数(即() )。

Note how it works:注意它是如何工作的:

fn f a n == [a, (\x _ -> f x) a (), (\x _ -> f x) ((\x _ -> f x) a ()) (), ...]
         == [a, f a, f (f a), ...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM