开发者

F# map/set comprehensions

开发者 https://www.devze.com 2023-04-12 02:41 出处:网络
I\'m looking for something akin to the dict/list/set comprehensions in Python. In Python you can do: [x+2 for x in list if x > 10]

I'm looking for something akin to the dict/list/set comprehensions in Python. In Python you can do:

[x+2 for x in list if x > 10]

and in F#

[for x in list do if x > 10 yield x+2]

but in Python, you can also do:

{x+2 for x in list if x > 10}

to generate Sets, and

{k: (v+10)/2 for k, v in list.items() if k > 5}

to generate Dicts. Is there any equivalent (both in terms of functio开发者_Python百科n and in terms of overall tidyness) syntax for this sort of thing in F#?


There is a set function accepting seq<_>, so you can do:

set [for x in list do if x > 10 yield x+2]

Same with dict. Here are the relevant docs:

set: http://msdn.microsoft.com/en-us/library/ee353747.aspx
dict: http://msdn.microsoft.com/en-us/library/ee353774.aspx


Essentially F# does not have a special syntax for this but you can use array or list comprehension and pass the result to functions provided to the standard library.

let intSet = set [for x in list do if x > 10 yield x+2]


let intMap = dict [for (x, y) in list do if x > 10 yield (x,y+2)]
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号