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 开发者_如何学Goappreciated!
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]
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.
精彩评论