在F#中的列表理解 [英] list comprehension in F#

查看:104
本文介绍了在F#中的列表理解的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在F#中做一些列表理解。我找到了这个

  let evens n = 
{for x in 1 .. n when x%2 = 0 - > x}
print_any(evens 10)

let squarePoints n =
{for x in 1 .. n
for y in 1 .. n - > x,y}
print_any(squarePoints 3)

第一个仍然正常,但第二是过时的。最新的(1.9.7.8)F#编译器不支持这种风格。



经过一番搜索,我发现这个作品

  let vec1 = [1; 2; 3] 
let vec2 = [4; 5; 6]
let products = [for x in vec1 do for y in vec2 do yield x * y]

有人可以指出语法的改变吗?谢谢。

解决方案


  • 嵌套for循环需要 do


  • 您需要使用 seq {..} {..} 没有 seq 的表单不再适用。


  • 当在中保护循环模式时,也不再受支持。 p>


  • print_any东西已弃用。使用 printf%A取而代之。




代码应该工作:

  let evens n = 
seq {for x in 1 .. n do if x%2 = 0 then x}
printf%A(evens 10)

let squarePoints n =
seq {for x in 1 .. n do
for y in 1 .. n - > x,y}
printf%A(squarePoints 3)

您仍然可以使用 $ b

 <$ c    - > 如果您只想返回一个值, $ c> let vec1 = [1; 2; 3] 
let vec2 = [4; 5; 6]
let products = [for vec1 do for y in vec2 - > x * y]

顺便说一下,我发现看看F#随着时间的推移是如何演变的。太糟糕了,早期的采用者已经在书架上放了部分过时的书(不是我介意的)。


I am trying to do some list comprehension in F#. And I found this.

let evens n =
    { for x in 1 .. n when x % 2 = 0 -> x }
print_any (evens 10)

let squarePoints n =
    { for x in 1 .. n
      for y in 1 .. n  -> x,y }
print_any (squarePoints 3)

The first still works ok, but the second is outdated. The latest (1.9.7.8) F# compiler does not support this style.

After some search I found this works

let vec1 = [1;2;3]
let vec2 = [4;5;6]
let products = [for x in vec1 do for y in vec2 do yield x*y]

Can someone point why the syntax changed? Thanks.

解决方案

  • Nested for loops require a do.

  • You need to use seq {..}. The form {..} without seq doesn't work anymore.

  • A when guard in a for loop pattern is also not supported anymore.

  • print_any something is deprecated. Use printf "%A" something instead.

This code should work:

let evens n =
    seq { for x in 1 .. n do if x%2=0 then yield x }
printf "%A" (evens 10)

let squarePoints n =
    seq { for x in 1 .. n do
            for y in 1 .. n  -> x,y }
printf "%A" (squarePoints 3)

You can still use the -> if all you want to do is return a single value:

let vec1 = [1;2;3]
let vec2 = [4;5;6]
let products = [for x in vec1 do for y in vec2 -> x*y]

By the way, I find it interesting to see how F# evolved over time. Too bad the early adopters have partially outdated books on their shelves (not that I mind).

这篇关于在F#中的列表理解的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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