cons :: operator for sequences in F#?
Asked Answered
P

3

5

Is there a better code that does not need to transform the sequence into 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)
Pytlik answered 1/3, 2012 at 16:18 Comment(0)
O
5

This is a great place to use Seq.fold. It collapses a collection down into a single value.

Cartesian keys1 keys2
|> Seq.fold (fun map (i, j) ->
  let value = (inputd.[i]).[j]
  Map.add (i, j) value map) Map.empty
Odalisque answered 1/3, 2012 at 16:23 Comment(1)
I just realised that. i dont know where was my head.Pytlik
F
5
Cartesian keys1 keys2
|> Seq.map (fun (i, j) -> ((i, j), (inputd.[i]).[j]))
|> Map.ofSeq
Furthermore answered 1/3, 2012 at 16:32 Comment(0)
S
5

As a complement to the previous answers, if you want to be able to pattern-match sequences, 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
Stipel answered 2/3, 2012 at 11:28 Comment(1)
Sadly, this active pattern appears to be orders of magnitude slower than a list's cons operator.Harter

© 2022 - 2024 — McMap. All rights reserved.