基于集合的多作业

编程入门 行业动态 更新时间:2024-10-24 06:26:38
本文介绍了基于集合的多作业的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

编辑

最初的问题是Collection to Tuple,因为我假设我需要一个元组才能进行可变的多重赋值。事实证明,可以直接对集合进行可变的多重赋值。

有一个简单的Seq [String]派生自一个正则表达式,我想转换为

我目前有:

这是最直接的方法是什么?

val(clazz,date)= captures match { case x:Seq [String] =& (x(0),x(1))}

我的路由层有一堆regex匹配的路由,我将做val(a,b,c)多重赋值on(捕获组总是知道,因为如果regex不匹配路由不处理)。比较匹配{case .. => ..}会更好一个精简的解决方案

在Scala中将集合转换为元组最短的1-liner是什么? p>

解决方案

这不是问题的答案,但可能以不同的方式解决问题。

你知道你可以匹配 xs:List [String] ,如下所示:

val a :: b :: c :: _ = xs

这将列表的前三个元素分配给 a,b,c ?您可以在 val 的声明中匹配 Seq 的其他内容,就像在 语句。请务必注意匹配的错误:

Scala模式匹配和try / catch

Edit

originally the question was "Collection to Tuple" as I assumed I needed a tuple in order to do variable multi-assignment. It turns out that one can do variable multi-assignment directly on collections. Retitled the question accordingly.

Original Have a simple Seq[String] derived from a regex that I would like to convert to a Tuple.

What's the most direct way to do so?

I currently have:

val(clazz, date) = captures match { case x: Seq[String] => (x(0), x(1)) }

Which is ok, but my routing layer has a bunch of regex matched routes that I'll be doing val(a,b,c) multi-assignment on (the capture group is always known since the route is not processed if regex does not match). Would be nice to have a leaner solution than match { case.. => ..}

What's the shortest 1-liner to convert collections to tuples in Scala?

解决方案

This is not an answer to the question but might solve the problem in a different way.

You know you can match a xs: List[String] like so:

val a :: b :: c :: _ = xs

This assigns the first three elements of the list to a,b,c? You can match other things like Seq in the declaration of a val just like inside a case statement. Be sure you take care of matching errors:

Scala pattern matching and try/catch

更多推荐

基于集合的多作业

本文发布于:2023-11-24 03:33:50,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1623824.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:多作

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!