kelperg1
kelperg1

Reputation: 81

F# How to append an element to the end of a list

How do I append a value to the end of a list?

let rec add lst value =
        match lst with
        | [] -> [value]

This currently only appends an empty list with the value x. How would I add a value to the end of a list that has elements in already in it?

Upvotes: 2

Views: 1536

Answers (1)

user1981
user1981

Reputation: 586

For simple recursive version use

let rec add lst value =
    match lst with
    | [] -> [ value ]
    | h :: t -> h :: add t value

Note that this implementation is not tail recursive.

But in pratice use the built in append operator

let add lst value = lst @ [ value ]

Or the standard function List.append which has the arguments in an other order.

let add lst value = List.append [ value ] lst

Also worth knowingis that append is an expensive function on a singly linked immutable list which create a new copy of the entire list.

Upvotes: 5

Related Questions