Danny
Danny

Reputation: 3665

F# replace first element in list?

Hey, I'm trying to learn some f# basics and am stumbling along. I'm wondering how you would go about "replacing" the first element in a list.

Any help would be appreciated!

Upvotes: 1

Views: 1577

Answers (2)

JaredPar
JaredPar

Reputation: 755141

Here's a general purpose function. It will replace the head of a list with a new value if the list is non-empty, else it will return a single element list with the replace value.

let replaceHead newHead list = 
  match list with
  | _ :: tail -> newHead :: tail
  | [] -> [newHead]

Upvotes: 4

Johan Kullbom
Johan Kullbom

Reputation: 4243

You could 'cons' (using the ::-operator) the new first element to the tail (List.tail) of the original list:

let theList = [1; 2; 3; 4]
let firstReplaced = 0 :: (List.tail a)

Note that this will leave the original list (theList) untouched.

Upvotes: 1

Related Questions