JC_
JC_

Reputation: 51

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

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

Upvotes: 4

Views: 462

Answers (2)

Curt Nichols
Curt Nichols

Reputation: 2767

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.

Upvotes: 3

glennsl
glennsl

Reputation: 29106

It returns the empty list because you return li which you have bound to the empty list. Remember that most values are immutable in F#. x @ li does not change the list pointed to by li in any way.

Here's what your code does, expression by expression:

let li = []

binds the empty list to the name li

x @ li

evaluates to x appended to li, but changes neither of them. And since li is the empty list, this is equivalent to just x. It effectively does nothing.

List.map(fun (x: 'a list) -> x @ li ) list

maps each element of list according to the function passed to it, which we just determined to do nothing. Hence this just creates a one-to-one copy of list.

let q = ...

assigns the copied list to q, which is then just discarded since it's not used anywhere.

li

returns the empty list.

Might I recommend that you start with a tutorial that teaches you the basic concepts underlying F# first? Trial-and-error is usually not a good approach to learning a programming language, and Stack Overflow isn't well suited as a mentoring service.

Upvotes: 2

Related Questions