F# Add an element to a sequence

f#
13,665

Solution 1

Seq.append:

> let x = { 1 .. 5 };;

val x : seq<int>

> let y = Seq.append x [9];; // [9] is a single-element list literal

val y : seq<int>

> y |> Seq.toList;;
val it : int list = [1; 2; 3; 4; 5; 9]

Solution 2

You can also use

let newSeq = Seq.append oldSeq (Seq.singleton newElem)

Which is a slight modification of the first answer but appends sequences instead of a list to a sequence.

given the following code

let startSeq = seq {1..100}
let AppendTest = Seq.append startSeq [101] |> List.ofSeq
let AppendTest2 = Seq.append startSeq (Seq.singleton 101) |> List.ofSeq
let AppendTest3 = seq { yield! startSeq; yield 101 } |> List.ofSeq

looped 10000 executions the run times are

Elapsed 00:00:00.0001399
Elapsed 00:00:00.0000942
Elapsed 00:00:00.0000821

Take from that what you will.

Solution 3

There's also an imperative solution...

> let x = seq {1..5}
> let y = seq { yield! x; yield 9 }  // Flatten the list,then append your element
> Seq.to_list y;;
val it : int list = [1; 2; 3; 4; 5; 9]

This may be better if the underlying problem is an imperative one, and it is most natural to use a yield statement in a loop.

let mySeq = seq { for i in 1..10 do yield i };;
Share:
13,665

Related videos on Youtube

pistacchio
Author by

pistacchio

Updated on April 15, 2022

Comments

  • pistacchio
    pistacchio about 2 years

    a simple question I cannot find an answer to: how to add an element to a sequence? Eg I have a seq and a newElem XElement I'd like to append to it.

    Thanks