我想知道我们是否可以使用purrr'smap和reduce来创建类似于 JavaScript 中的这个函数的斐波那契函数:
function fib(n){
return new Array(n).fill(1).reduce((arr, _ ,i) => {
arr.push((i <= 1) ? i : arr[i-2] + arr[i-1])
return arr
},[]) ;
}
console.log(fib(10))
Run Code Online (Sandbox Code Playgroud)
我在这里看到R中使用递归的斐波那契数列的答案,但我想知道我们是否可以专门使用 purrr reduce,如果可以,如何使用?
我认为purrr::accumulate()更适合这项任务:
n <- 10 # Desired number of values
purrr::accumulate( .init = c(0L,1L), # Starting with (0,1)
rep(0,n), # Accumulate n times
~c(.x,sum(.x))[2:3] # (x,y) -> (x, y, x+y)[2:3]
) %>%
purrr::map_int( `[`, 1 ) # (x,y) -> x
# [1] 0 1 1 2 3 5 8 13 21 34 55
Run Code Online (Sandbox Code Playgroud)
该解决方案的关键是要保持对值的整个accumulate()呼叫:(0,1),(1,1),(1,2)等等,因为你需要在前两个值来计算新的。
然后检索每对的第一个元素。