2014-10-26 66 views
3
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) 
} 
+2

這是scala中最簡單的形式。 – 2014-10-26 23:14:56

+0

F#將所有參數作爲單個元組處理。如果斯卡拉也可以做到這一點,那就太棒了。 – Grozz 2015-02-05 20:46:50

回答

0

雖然這可能看起來像一個簡單的建議,f功能,可以通過只使用_1_2在對記錄進行進一步簡化。

def f(tuple: (Int, Int)): Unit = 
    do_something(tuple._1, tuple._2) 

顯然,通過這樣做,你會影響可讀性(約1樓和元組的第二個參數的含義是去掉了一些元數據信息),你應該要使用的元組中某處的元素f方法,你將需要再次提取它們。

雖然對於許多用途來說,這仍然是最簡單,最短和最直觀的選擇。

+0

這就像使用'list.map(tuple => do_something(tupple._1,tupple._2))''。它不太可讀。 – 2014-10-27 00:22:15

0

如果我理解正確,你試圖將一個元組傳遞給一個帶有2個參數的方法?

def f(tuple: (Int,Int)) = do_something(tuple._1, tuple._2) 
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對每FunctionNN >= 2限定,並且返回一個函數期望包裹在一個元組中的參數。

+0

作爲一個例子,我在'f()'內調用了'do_something(a,b)'。我其實不想創建外部函數'do_something'。所以,我正在尋找一個更可讀的'def f(tuple:(Int,Int))= tuple._1 + tuple._2'版本。 (通過更具可讀性,我的意思是給變量名稱,而不是在元組上使用_1和_2)。 – 2014-10-27 00:26:51

0

通過更具可讀性,我的意思是讓變量名,而不是使用_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)不起作用。