简体   繁体   English

怎么在haskell做这个? [x ^ 0,x ^ 1,x ^ 2,x ^ 3 ...]

[英]how to do this in haskell ? [x^0,x^1,x^2,x^3 …]

i want to have a list like this one 我想要一个像这样的列表

[x^0,x^1,x^2,x^3 ...] 

is it possible to have such a list 是否有可能有这样的清单

for example 例如

 ex : x = 2   [1,2,4,8,16,32 ..] 

You can use iterate or unfoldr to double a number many times. 您可以使用iterateunfoldr多次翻倍。 This could be more efficient than computing x^n for each n . 这可能比为每个n计算x^n更有效。

Below, I use x=2 , but you can use any x . 下面,我使用x=2 ,但你可以使用任何x

> take 10 $ iterate (*2) 1
[1,2,4,8,16,32,64,128,256,512]
> take 10 $ unfoldr (\x -> Just (x,2*x)) 1
[1,2,4,8,16,32,64,128,256,512]

Also beware that bounded integer types such as Int will overflow pretty fast in this way. 还要注意像Int这样的有界整数类型会以这种方式快速溢出。

Yes, it is pretty easy thing to do in haskell. 是的,在haskell中这很容易。

You create an infinite stream of positive numbers and then map over them with function n ↦ x^n 您创建一个无限的正数流,然后用函数n ↦ x^n映射它们

f :: Num a => a -> [a]
f x = fmap (\n -> x^n) [0..]

> take 10 (f 2)

[1,2,4,8,16,32,64,128,256,512]

In Haskell, the list is linear no matter the progression. 在Haskell中,无论进展如何,列表都是线性的。 By linear, I mean non-recursive. 线性,我的意思是非递归。 The elements in the list are not dependent on one or more previous elements or an initial element. 列表中的元素不依赖于一个或多个先前元素或初始元素。

In Haskell such lists are used very much. 在Haskell中,这些列表非常用。 In Haskell there are two primary facilities for producing such lists. 在Haskell中,有两个主要设施用于生成此类列表。 The first is map and it is effective without any filtering or recursion. 第一个是map ,它没有任何过滤或递归是有效的。

f b n = map (b^) [0..n]

The second is the list comprehension 第二是列表理解

f b n = [b^x|x<-[0..n]]

In both it is simple to set the limit or number of elements in the result. 两者都很容易在结果中设置元素的限制或数量。 These could both be made into infinite lists if desired by excluding the n in both the left and right side of the equations. 如果需要,可以通过排除方程左侧和右侧的n来将它们都制成无限列表。

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

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