I am getting my F#eet wet and having a hard time getting my head around simple concepts. Please oblige me by helping with this question, NOT homework!
Say I have a list [1;2;3;4]
How do I transform it into list of all possible combinations of the list's elements:
[(1,2);(1,3);(1,4);(2,3);(2,4);(3,4)]
?
What I have come up with:
let tuples=
let lst=[1;2;3;4]
List.map (fun i->(i,i)) lst
Obviously this gives the wrong result, but how to proceed? Do I simply need to use the nested for loops approach that I would take writing this code in C#?
You could use recursion to achieve this, I believe this is called the "cons pattern"
open NUnit.Framework
open Swensen.Unquote
let convert input =
let rec loop remain acc =
match remain with
| x :: xs ->
let combos = xs |> List.map (fun i -> (x,i))
loop xs (acc@combos)
| x -> acc
loop input []
[<Test>]
let TheTest () =
let actual = convert [1;2;3;4]
let expected = [(1,2);(1,3);(1,4);(2,3);(2,4);(3,4)]
test <@ expected = actual @>
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments