Is there something like List.init, but of the form "int -> 'T -> 'T list" instead?
I am looking for a way to try to simplify the following expression, which looks ugly, IM开发者_运维百科O:
List.map (fun _ -> generateIndividual()) [1..popSize]
I found about List.init
, but it still isn't really what I am looking for:
List.init popSize (fun x -> generateIndividual())
It'd be perfect gave it not an argument to the lambda expression. It'd be perfect this way:
List.init popSize generateIndividual()
Is there something in the F# library that'd help me clean this up?
Thanks
Thanks to the fact that unit(void) is also a type you can do this:
List.init popSize (ignore >> generateIndividual)
Not really. The nearest solution would be to alter the definition of your generateIndividual
function so that it accepts a value of any type (rather than just the value of the type unit
) and discards it:
let generateIndividual _ = ...
Then you could write:
List.init popSize generateIndividual
Another solution is to use a list comprehension:
[for _ in 1..popSize -> generateIndividual()]
You could do:
[ for i = 1 to popSize do
yield generateIndividual() ]
How about this?
let generateIndividual dummy = 4
let popSize = 10
let lst = List.init popSize generateIndividual
You can create an extension like this:
module List =
let init2 count f = List.init count (fun _ -> f())
You can then call it like this:
List.init2 5 generateIndividual
I know, late and all, but:
- This solution is as short as you'll get,
Unlike ebb's (which you've chosen), this one will execute side-effects once:
(fun a -> Array.create a >> List.ofArray)
The type is exactly (int -> 'a -> 'a list), only disadvantage is conversion from Array to List, but this is still a bit better performance-wise than converting Seq to List (which is what done by list expressions).
精彩评论