Search code examples
f#seq

How to apply Seq map function?


I been recently playing with F# . I was wondering instead of using a for loop to generate a sequence to element which are multiplied with every other element in the list how can I use a Seq map function or something similar to generate something like below.

So for e.g. I have a list [1..10] I would like to apply a fun which generates a result something like

[(1*1); (1*2);(1*3); (1*4); (1*5)......(2*1);(2*2);(2*3).....(3*1);(3*2)...]

How can i achieve this ?.

Many thanks for all you help.


Solution

  • let list = [1..10]
    
    list |> List.map (fun v1 -> List.map (fun v2 -> (v1*v2)) list) |> List.collect id
    

    The List.collect at the end flattens the list of lists. It works the same with Seq instead of List, if you want a lazy sequence.

    Or, using collect as the main iterator, as cfern suggested and obsessivley eliminating anonymous functions:

    let flip f x y = f y x
    
    let list = [1..10]
    
    list |> List.collect ((*) >> ((flip List.map) list))