val list = List((1,2), (3,4))
list.map(tuple => {
val (a, b) = tuple
do_something(a,b)
})
// the previous can be shortened as follows
list.map{ case(a, b) =>
do_something(a,b)
}
// similarly, how can I shorten this (and avoid declaring the 'tuple' variable)?
def f(tuple: (Int, Int)) {
val (a, b) = tuple
do_something(a,b)
}
// here there two ways, but still not very short,
// and I could avoid declaring the 'tuple' variable
def f(tuple: (Int, Int)) {
tuple match {
case (a, b) => do_something(a,b)
}
}
def f(tuple: (Int, Int)): Unit = tuple match {
case (a, b) => do_something(a,b)
}
回答
雖然這可能看起來像一個簡單的建議,f
功能,可以通過只使用_1
和_2
在對記錄進行進一步簡化。
def f(tuple: (Int, Int)): Unit =
do_something(tuple._1, tuple._2)
顯然,通過這樣做,你會影響可讀性(約1樓和元組的第二個參數的含義是去掉了一些元數據信息),你應該要使用的元組中某處的元素f
方法,你將需要再次提取它們。
雖然對於許多用途來說,這仍然是最簡單,最短和最直觀的選擇。
這就像使用'list.map(tuple => do_something(tupple._1,tupple._2))''。它不太可讀。 – 2014-10-27 00:22:15
如果我理解正確,你試圖將一個元組傳遞給一個帶有2個參數的方法?
def f(tuple: (Int,Int)) = do_something(tuple._1, tuple._2)
使用tupled
scala> def doSomething = (a: Int, b: Int) => a + b
doSomething: (Int, Int) => Int
scala> doSomething.tupled((1, 2))
res0: Int = 3
scala> def f(tuple: (Int, Int)) = doSomething.tupled(tuple)
f: (tuple: (Int, Int))Int
scala> f((1,2))
res1: Int = 3
scala> f(1,2) // this is due to scala auto-tupling
res2: Int = 3
tupled
對每FunctionN
與N >= 2
限定,並且返回一個函數期望包裹在一個元組中的參數。
作爲一個例子,我在'f()'內調用了'do_something(a,b)'。我其實不想創建外部函數'do_something'。所以,我正在尋找一個更可讀的'def f(tuple:(Int,Int))= tuple._1 + tuple._2'版本。 (通過更具可讀性,我的意思是給變量名稱,而不是在元組上使用_1和_2)。 – 2014-10-27 00:26:51
通過更具可讀性,我的意思是讓變量名,而不是使用_1 _2的元組
在這種情況下,這是一個好主意,用一個案例類,而不是一個元組,特別是因爲只需要一條線:
case class IntPair(a: Int, b: Int)
def f(pair: IntPair) = do_something(pair.a, pair.b)
如果你從不能被改變(或者你不想改變)外部代碼(Int, Int)
,你可以添加一個方法,從一個元組轉換爲IntPair
。
另一種選擇:{(a: Int, b: Int) => a + b}.tupled.apply(tuple)
。不幸的是,{case (a: Int, b: Int) => a + b}.apply(tuple)
不起作用。
- 1. 斯卡拉元組提取
- 2. 斯卡拉宏快捷
- 3. 斯卡拉功能組合
- 4. 提取方法,以獨立的功能斯卡拉
- 5. 斯卡拉 - 元組
- 6. 斯卡拉:在元組
- 7. 斯卡拉功能組合與未來
- 8. 斯卡拉組合功能未終止
- 9. 斯卡拉功能語法
- 10. 澄清斯卡拉功能
- 11. 斯卡拉鑄造功能
- 12. 斯卡拉設置功能
- 13. 斯卡拉:「使用」功能
- 14. 斯卡拉 - 減少功能
- 15. 從斯卡拉功能
- 16. 斯卡拉 - 返回地圖功能在斯卡拉
- 17. 我的功能的快捷方式
- 18. Xcode:高亮功能的快捷方式
- 19. PHP功能(快捷方式)使用
- 20. 反轉Multimap之以功能性的方式在斯卡拉
- 21. 如何提取斯卡拉
- 22. 斯卡拉找到元組
- 23. 斯卡拉元組解構
- 24. 斯卡拉元組選
- 25. TortoiseSVN提交快捷方式
- 26. 合成功能「##」在斯卡拉
- 27. 如何在斯卡拉咖喱功能
- 28. 快速功能或快捷方式在連接字符串
- 29. 鏈接斯卡拉部分功能的優雅方式
- 30. 斯卡拉 - 以功能方式修改字符串
這是scala中最簡單的形式。 – 2014-10-26 23:14:56
F#將所有參數作爲單個元組處理。如果斯卡拉也可以做到這一點,那就太棒了。 – Grozz 2015-02-05 20:46:50