Add elements to a sequence

226 views Asked by At

I have a csv file I am reading from

Din, Anh , 69
James, Urbank,61

I want to add another name " Ernest , Cuban , 70 " to the csv string , so I first delimited each values with the comma. I started looking for an insert function and found one so I added this line to my code

 |>Seq.map (fun values -> 
         values.[0].Insert(0,"Ernest")),
         values.[1].Insert(0,"Cuban")),
         float values.[2].Insert(0,"70"))

Obviously that didn't work what ends up happening is the Ernest is added to the beginning of Din and James , Cuban to the beginning of Anh and Urbank , and 70 to the beginning of 69 and 61.

ErnestDin , CubanAnh , 7061

So my question is how can I add those values to my seq , keeping in mind that Ernest would be in the middle of both Din and James as the sequence has to be in alphabetical order . I researched and found the Map.add that gave me an alphanumerical number as a result and the Seq.Append seems to only be working with integers.

2

There are 2 answers

1
Mark Seemann On

Sequences in F# are immutable, so you can't just insert data into them. If your data set isn't too big, the easiest solution may simply be to add the new data to the head of a list, and then sort it:

> let data = [("Din", "Anh" , 69); ("James", "Urbank", 61)];;

val data : (string * string * int) list =
  [("Din", "Anh", 69); ("James", "Urbank", 61)]

> ("Ernest", "Cuban", 70) :: data |> Seq.sort;;
val it : seq<string * string * int> =
  seq [("Din", "Anh", 69); ("Ernest", "Cuban", 70); ("James", "Urbank", 61)]

Note that this most likely isn't the most efficient solution, but it's Easy :)

0
polkduran On

You can build a new sequence using the seq constructor that yields your original sequence and the new element.

Let's say you have a function that takes the new element and the original sequence:

let appendElement (row:'a) (s:seq<'a>) = seq{
            yield! s
            yield row
        }

let data = [("Din", "Anh" , 69); ("James", "Urbank", 61)] // which is also a sequence

let newData = data 
                |> appendElement ("Ernest", "Cuban", 70) 
                |> appendElement ("Other", "Other", 5) 
                |> List.ofSeq

List.ofSeq will iterate the sequence with the new elements, you can remove it if you are iterating your sequence later. As you are working with sequences, it will be more efficient than manipulating lists.