如何生成乘法表序列?
我想生成一个像乘法表一样的序列。因此,对于 1 的开始和 10 的停止,我正在寻找一个像
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // 1*1 - 1*10
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, // 2*1 - 2*10
3, 6, 9, 12, ... // 3*1 - 3*10
Here is my lame start at it 的序列,但是我似乎无法弄清楚如何在到达停止时干净地递增 j ,或者如何重置我回到起点。
let multable (start,stop) =
(start,start)
|> Seq.unfold(
fun (i,j) ->
Some(i*j, (i+1, j)))
let its = multable(1, 1)
let first10 = Seq.take 10 its
printf "%A" (Seq.to_list first10)
这当然给了我 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
I want to generate a sequence like a multiplication table. So for a start of 1 and a stop of 10 I am looking for a sequence like
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // 1*1 - 1*10
2, 4, 6, 8, 10, 12, 14, 16, 18, 20, // 2*1 - 2*10
3, 6, 9, 12, ... // 3*1 - 3*10
Here is my lame start at it, however I can't seem to figure out how to cleanly increment j when the stop is reached, or how to reset i back to the start.
let multable (start,stop) =
(start,start)
|> Seq.unfold(
fun (i,j) ->
Some(i*j, (i+1, j)))
let its = multable(1, 1)
let first10 = Seq.take 10 its
printf "%A" (Seq.to_list first10)
Which of course gives me 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我真的想不出很多情况下我更喜欢
Seq.unfold
而不是等效的列表理解:有时 Array.init 方法也很有用:
I can't really think of many cases where I'd prefer
Seq.unfold
over an equivalent list comprehension:Occasionally the Array.init methods are useful too:
使用序列表达式:
输出:
以这种方式表示基本的二维结构很奇怪。为什么不是序列的序列:
输出:
如果你想变得“聪明”并避免乘法:
我实际上没有在理解/序列表达式之外看到任何好的预先打包的“从 a 到 b 的序列”,尽管显然有 [a. .b](列表)和 [|a..b|](数组),您可以通过 Seq.unfold、Seq.map 等进行投影以生成 Seq。
Use a sequence expression:
Output:
It's weird to represent a fundamentally 2d structure in this fashion. Why not a sequence of sequences:
Output:
If you want to be "clever" and avoid multiplication:
I don't actually see any nice prepackaged "sequence from a to b" outside of comprehensions/sequence expressions, although there's obviously [a..b] (list) and [|a..b|] (array) which you can project through Seq.unfold, Seq.map, etc. to make a Seq.
这是使用序列的另一种方法:
Here's another way to use sequences: