Cons :: operator for sequences in F #?

Is there any better code that doesn't need to convert a sequence to a list?

let rec addentry map keys = match keys with | ((i,j) :: tail) -> Map.add (i,j) ((inputd.[i]).[j]) (addentry map tail) | ([]) -> map addentry Map.empty (Cartesian keys1 keys2 |> Seq.toList) 
+4
source share
3 answers

This is a great place to use Seq.fold . He collapses the collection into one value.

 Cartesian keys1 keys2 |> Seq.fold (fun map (i, j) -> let value = (inputd.[i]).[j] Map.add (i, j) value map) Map.empty 
+5
source
 Cartesian keys1 keys2 |> Seq.map (fun (i, j) -> ((i, j), (inputd.[i]).[j])) |> Map.ofSeq 
+5
source

As a complement to the previous answers, if you want to be able to sequence with a pattern, you can define an active pattern:

 let (|Cons|Nil|) s = if Seq.isEmpty s then Nil else Cons(Seq.head s, Seq.skip 1 s) let rec addentry map keys = match keys with | Cons((i,j), tail) -> Map.add (i,j) ((inputd.[i]).[j]) (addentry map tail) | Nil -> map 
+5
source

Source: https://habr.com/ru/post/1399217/


All Articles