如何将函数应用于元组? [英] How to apply a function to a tuple?

查看:42
本文介绍了如何将函数应用于元组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该很容易.如何将函数应用于 Scala 中的元组?可视化:

<前>scala> def f (i : Int, j : Int) = i + jf: (Int,Int)Int标量 > val p = (3,4)p: (Int, Int) = (3,4)标量> f p:6: 错误:在对象 $iw 中缺少方法 f 的参数;如果要将其视为部分应用函数,请使用_"遵循此方法压力^标度> f _ p:6: 错误:值 p 不是 (Int, Int) => Int 的成员f_p^标度> (f _) p:6: 错误:值 p 不是 (Int, Int) => Int 的成员(f _) p^标量> f(p):7: 错误: 方法 f 的参数数量错误: (Int,Int)Intf(p)^斯卡拉> 呸!

非常感谢.

解决方案

在 Scala 2.8 及更新版本中:

scala>def f (i : Int, j : Int) = i + jf: (i: Int,j: Int)Int//注意 f 后面的下划线标度>val ff = f _ff: (Int, Int) =>Int = <function2>标度>val fft = ff.tupledfft: ((Int, Int)) =>Int = <function1>

在 Scala 2.7 中:

scala>def f (i : Int, j : Int) = i + jf: (Int,Int)Int//注意 f 后面的下划线标度>val ff = f _ff: (Int, Int) =>Int = <函数>标度>val fft = Function.tupled(ff)fft: ((Int, Int)) =>Int = <函数>

This should be an easy one. How do I apply a function to a tuple in Scala? Viz:

scala> def f (i : Int, j : Int) = i + j
f: (Int,Int)Int

scala> val p = (3,4)
p: (Int, Int) = (3,4)

scala> f p
:6: error: missing arguments for method f in object $iw;
follow this method with `_' if you want to treat it as a partially applied function
       f p
       ^

scala> f _ p
:6: error: value p is not a member of (Int, Int) => Int
       f _ p
           ^

scala> (f _) p
:6: error: value p is not a member of (Int, Int) => Int
       (f _) p
             ^

scala> f(p)
:7: error: wrong number of arguments for method f: (Int,Int)Int
       f(p)
       ^

scala> grr!

Many thanks in advance.

解决方案

In Scala 2.8 and newer:

scala> def f (i : Int, j : Int) = i + j
f: (i: Int,j: Int)Int

// Note the underscore after the f
scala> val ff = f _
ff: (Int, Int) => Int = <function2>

scala> val fft = ff.tupled
fft: ((Int, Int)) => Int = <function1>

In Scala 2.7:

scala> def f (i : Int, j : Int) = i + j
f: (Int,Int)Int

// Note the underscore after the f
scala> val ff = f _
ff: (Int, Int) => Int = <function>

scala> val fft = Function.tupled(ff)
fft: ((Int, Int)) => Int = <function>

这篇关于如何将函数应用于元组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆