地图不需要在Scala中推断出codomain?

问题描述 投票:0回答:2

以下Scala代码:

val l = List((1,2),(2,3),(3,4))
def fun1(t1: Int,t2: Int) = (t1+1,t2)
l map fun1

给出错误:

Error:(3, 8) type mismatch;
 found   : (Int, Int) => (Int, Int)
 required: ((Int, Int)) => ?
l map fun1;}
      ^

我想知道为什么map必须有一个codomain没有推断类型的函数...

scala functional-programming
2个回答
6
投票

这不是关于codomain,它是错误的函数arity。方法map期望一个函数有一个参数,即使这个参数是一个元组:

((Int, Int)) => (Int, Int) // Function[(Int, Int), (Int, Int)]

但是你传递的函数有两个参数(两个int):

(Int, Int) => (Int, Int)   // Function2[Int, Int, (Int, Int)]

这样做:

def fun1(t: (Int, Int)) = (t._1+1, t._2)
l map fun1

或这个:

def fun1(t1: Int,t2: Int) = (t1+1,t2)
l map { case (x, y) => fun1(x, y) }

这是a similar example with a more detailed explanation的类似问题。


3
投票

你必须使用case来破坏元组。

val l = List((1,2),(2,3),(3,4))
def fun1(t1: Int,t2: Int) = (t1+1,t2)
l map { case (a, b) => fun1(a, b) }

但是,如果你声明你的功能如下,使其工作

def fun1(t: (Int, Int)) = (t._1 + 1,t._2)

l map fun1
© www.soinside.com 2019 - 2024. All rights reserved.