I want to create a list that is the multiples of a number. For example [2; 4; 6; 8; 10] would be the multiples of 2 between 0 and 10.
How would I dynamically create such a list of the multiples of x? Is it possible to do it without setting an upper bound?
One way to do it would be to create a list between 0 and some crazy large number and then filter it using the mod function. Trying to test this, creating a list of 0 to some crazy large number caused an out of memory except开发者_开发知识库ion (after a 30 second or so wait).
I feel like F# has some super simple and awesome way to build such a list but I'm too much of a newb to know what it is, yet. Help?
This produces an infinite sequence of multiples:
let multiples n = Seq.unfold (fun i -> Some(i, i + n)) n
multiples 3 |> Seq.take 3 //seq [3; 6; 9]
This is a bit more code, but faster:
let multiples n =
let rec loop i =
seq {
yield i
yield! loop (i + n)
}
loop n
It's basically equivalent to the following C#:
static IEnumerable<int> Multiples(int n) {
int i = n;
while (true) {
yield return i;
i += n;
}
}
Sequences (IEnumerables) give the laziness you want here:
let multiplesOfN n =
seq {
for i in 1 .. 1000000 do
yield i * n
}
let first6multsof3 =
multiplesOfN 3 |> Seq.take 6
printfn "%A" (first6multsof3 |> Seq.toList)
or with your filter-mod strategy:
seq { 1 .. 1000000} |> Seq.filter (fun x -> x%3=0) |> Seq.take 6 |> Seq.toList
[ firstValue..Step..endValue]
[ 2..2..10] => [2; 4; 6; 8; 10]
other way
Seq.initInfinite id |> Seq.map (((+) 1) >> ((*) 2))
List.init 10 ((*) 3)
val it : int list = [0; 3; 6; 9; 12; 15; 18; 21; 24; 27]
You can play with the arguments and Seq.skip
to get whatever you need.
For example, for [2; 4; 6; 8; 10]
:
List.init 6 ((*) 2)
|> List.tail
Or:
List.init 6 ((*) 2)
|> Seq.skip 1
|> List.ofSeq
精彩评论