Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to concat a list of lists to a single list with list.map property

Tags:

f#

I need to create a single list from a list of lists using the List.map property in f#. This is what i got so far.

let lst1 = [[1;2;3;4];[5;6;7;8]]

let concat (list: 'a list list) =
    let li = []
    let q = List.map(fun (x: 'a list) -> x @ li ) list
    li


printfn "%A" (concat lst1)

I expect the output

li = [1;2;3;4;5;6;7;8]

but get an empty list instead.

I don't get why the list is empty. I'm adding to the list li in the List.map function

like image 469
JC_ Avatar asked Sep 06 '25 15:09

JC_


1 Answers

I would generally use List.concat for this purpose.

In FSI (the F# REPL):

> let lst1 = [[1;2;3;4];[5;6;7;8]];;
val lst1 : int list list = [[1; 2; 3; 4]; [5; 6; 7; 8]]

> List.concat lst1;;
val it : int list = [1; 2; 3; 4; 5; 6; 7; 8]

If you're seeking the challenge of writing this yourself, you might look into List.fold.

like image 191
Curt Nichols Avatar answered Sep 10 '25 12:09

Curt Nichols