Wednesday, May 7, 2014

Merge two List in F#

Merge is a function that takes two sorted lists in ascending order , and returns a sorted list in ascending order for example :

merge ([1;100;200],[2;3;4;100;101;300])
returned list [1;2;3;4;100;100;101;200;300]


let rec merge (L1,L2) =
match L1,L2 with
| [ ] ,[ ] ->[ ]
| _ ,[  ] ->L1
| [ ] ,_  -> L2
| _ , _ ->   if L1.Head < L2.Head then  L1.Head::merge(L1.Tail , L2)
                else  L1.Head::merge(L1, L2.Tail)


let R2 = merge([1;100;200],[2;3;4;100;101;300])
printfn "%A" R2

No comments:

Post a Comment