仅转换Scala列表的第一个元素 [英] Transform only the first element of a Scala list

查看:103
本文介绍了仅转换Scala列表的第一个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  val head = l1.head 
val tail = l1.tail
val l2 = change(head):: tail

已更新()看起来可能会起作用,但没有太大的改善:

  val head = l1.head 
val l2 = l.update(0,change(head))

我喜欢这样:

  val l2 = l1。 updateHead(change(_))

有什么吗?

解决方案

您可以尝试使用模式匹配

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

这样你就不必担心如果 head 实际返回元素


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?

解决方案

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

这篇关于仅转换Scala列表的第一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆