Transform only the first element of a Scala list

dictionary, list, scala

Solution

you could try using pattern matching

val l2 = l1 match{
    case Nil   => Nil
    case x::xs => change(x)::xs
}

That way you don't have to worry if `head` actually returns an element

Problem

Is there a way to transform only the first element of a list without doing something super hacky like: ``` val head = l1.head val tail = l1.tail val l2 = change(head) :: tail ``` `updated()` looks like it could work, but isn't much of an improvement: ``` val head = l1.head val l2 = l.update(0, change(head)) ``` I'd love something like: ``` val l2 = l1.updateHead(change(_)) ``` Is there anything like that?

Original source