这个函数(haskell)发生了什么? [英] What is going on in this function (haskell)?

查看:94
本文介绍了这个函数(haskell)发生了什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  ns :: [Integer] 
我有这个haskell函数,我不太明白。 ns = 0:[n + k | (n,k)< - zip ns [1,3 ..]]

到需要3纳秒。



我认为ns是不变的,所以它只会压缩列表的第一个元素,给出(0,1)。然后,当添加给出答案1.然后它说取3纳秒,所以我压缩0与列表的前5个元素,给出...(0,1),(0,3),(0,5 ),然后添加时,我得到[1,3,5]的最终答案。然而,这不是正确的答案。



ns实际发生了什么?我努力去理解......

解决方案

haskell很懒,所以你可以有递归定义。

  ns = 0:某物

(n,k)< - zip(0:某物)[1,3,5,7 ...]
(n,k)< - [(0,1):某物)

ns = 0:1:某物

(n,k)< - zip(0:1:某物)[3,5,7 ...]
(n,k)< - (0,1):(1,3):something

ns = 0:1:4:something

(n,k)< - zip(0 :1:4:某物)[5,7 ...]
(n,k)< - (0,1):(1,3):(4,5):某物

ns = 0:1:4:9:某物

....

看看我们如何确定下一个元组是什么,然后添加它的两个元素。这允许我们确定下一个元素。


I have this haskell function that I don't quite understand.

ns :: [Integer]
ns = 0 : [n+k | (n, k) <- zip ns [1,3..]]

I am asked to "take 3 ns".

I thought ns was constant so it would only zip with the first element of the list, giving (0,1). Then when added gives an answer of 1. Then it says "take 3 ns" so I zipped 0 with the first 5 elements of the list, giving... (0,1),(0,3), (0,5) and then when added, I get a final answer of [1,3,5]. However this isn't the correct answer.

What is actually happening to ns? I'm struggling to understand...

解决方案

haskell is lazy so you can have recursive definitions. Here it is laid out.

ns = 0 : something

(n,k) <- zip (0 : something ) [1,3,5,7...]
(n,k) <- [(0,1) : something )

ns = 0 : 1 : something

(n,k) <- zip ( 0 : 1 : something ) [3,5,7...]
(n,k) <- (0,1) : (1,3) : something

ns = 0 : 1 : 4 : something

(n,k) <- zip ( 0 : 1 : 4 : something ) [5,7...]
(n,k) <- (0,1) : (1,3) : (4,5) : something

ns = 0 : 1 : 4 : 9 : something

....

See how we determine what the next tuple is then add its two elements. This allows us to determine the next element.

这篇关于这个函数(haskell)发生了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆