2017-06-14 240 views
0

對不起這個爛攤子。我仍然在Scala中取得進展。改寫所有的問題是:斯卡拉傳遞函數作爲參數傳遞給另一個函數

def func1(x: Double, y: Double) = { 
    x+y 
} 

def func2(x: Double, y: Double) = { 
    x-y 
} 

def calc(f: (Double, Double) => Double, z: Int) = { 
    f(1,2) + z 
} 

//Sometimes I want to call 
calc(func1(1,2), 3) 

//Other times 
calc(func2(1,2), 3) 

,我得到這個錯誤:

<console>:52: error: type mismatch; 
found : Double 
required: (Double, Double) => Double 
       calc(func1(1,2), 3) 
         ^

什麼是正確的方法來調用計算()?

感謝

+0

這不是傳遞函數作爲參數,而是傳遞函數的結果。 –

+0

是的,你是對的 – MLeiria

回答

0

首先,你正在使用VAR的是,這是不被認爲是很好的做法,如果你的地圖是指使用(不想去詳細瞭解更多信息閱讀this)在課堂上的本地可以創建一個可變映射。

現在回到你的問題: 如果你希望你的函數如預期那麼你應該確保doSomeComputation函數會返回一個由otherFunction有望作爲輸入參數,像這樣

值工作
def doSomeComputation(m1: Map[String, List[(String, Double)]], name: String) = { 
     (Map("some_key" -> List(("tuple1",1.0))), "tuple2") 
} 

返回類型爲(圖[字符串,列表[字符串,INT]],字符串)

但是它不會使你在做什麼太大的意義試着去做,我可以幫助你理解你是否可以清楚地提到你想要達到的目標。

1

請注意,在calc()正文中提供了參數f(),即12

def calc(f: (Double, Double) => Double, z: Int) = { 
    f(1,2) + z 
} 

因此,你不需要指定功能的任何參數的傳遞。

calc(func1, 3) 
calc(func2, 3) 
0

你需要傳遞函數簽名f: (Map[String,List[(String, Double)]], String) => Double而不僅僅是返回類型。下方的輕視例如:

var testMap: Map[String, List[(String, Double)]] = Map(
    "First" -> List(("a", 1.0), ("b", 2.0)), 
    "Second" -> List(("c", 3.0), ("d", 4.0)) 
) 
// testMap: Map[String,List[(String, Double)]] = Map(First -> List((a,1.0), (b,2.0)), Second -> List((c,3.0), (d,4.0))) 

def doSomeComputation(m1: Map[String, List[(String, Double)]], name: String): Double = { 
    m1.getOrElse(name, List[(String, Double)]()).map(x => x._2).max 
} 
// doSomeComputation: (m1: Map[String,List[(String, Double)]], name: String)Double 

def doSomeOtherComputation(m1: Map[String, List[(String, Double)]], name: String): Double = { 
    m1.getOrElse(name, List[(String, Double)]()).map(x => x._2).min 
} 
// doSomeOtherComputation: (m1: Map[String,List[(String, Double)]], name: String)Double 

def otherFunction(f: (Map[String, List[(String, Double)]], String) => Double, otherName: String) = { 
    f(testMap, "First") * otherName.length 
} 
// otherFunction: (f: (Map[String,List[(String, Double)]], String) => Double, otherName: String)Double 

println(otherFunction(doSomeComputation, "computeOne")) 
// 20.0 

println(otherFunction(doSomeOtherComputation, "computeOne")) 
// 10.0 

根據您的使用情況下,它可能是一個好主意,還通過testMapname作爲參數傳遞給otherFunction

相關問題