简体   繁体   中英

Creating a list or sequence of numbers up to a certain value in F#

Suppose I want to create a list or sequence of all cubic numbers under 5555, or fibonnacci numbers under 4500 - How would I do this?

I can generate a list or sequence of these , but I don't know how to make them terminate after a certain point.

In the case of the fibonacci sequence it is difficult to compute n such that F(n) is less than some x, so I require a solution that generates the elements of the list or sequence until one of the elements exceeds the upper bound.

In F#, you can use the seq<'T> type to work with lazily generated sequences. For example, to generate squares of all integers, you could write:

let rec integersFrom n = seq { 
  yield n
  yield! integersFrom (n + 1) }

let squares = seq {
  for n in integersFrom 0 do
    yield n * n }

The first function recursively generates a sequence of all integers (if this was using an unbounded numerical type, this would be "infinite"). The second applies a transformation.

As mentioned in the comment Seq.takeWhile lets you restrict the series. Say you want all squares smaller than 1000:

squares |> Seq.takeWhile (fun n -> n < 1000)

Then you can fully evaluate the series using eg List.ofSeq .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM