这应该很简单。如何将函数应用于Scala中的元组?即:
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!
非常感谢提前。
答案 0 :(得分:59)
在Scala 2.7中:
scala> def f (i : Int, j : Int) = i + j
f: (Int,Int)Int
scala> val ff = f _
ff: (Int, Int) => Int = <function>
scala> val fft = Function.tupled(ff)
fft: ((Int, Int)) => Int = <function>
在Scala 2.8中:
scala> def f (i : Int, j : Int) = i + j
f: (i: Int,j: Int)Int
scala> val ff = f _
ff: (Int, Int) => Int = <function2>
scala> val fft = ff.tupled
fft: ((Int, Int)) => Int = <function1>
答案 1 :(得分:10)
跟进另一个答案,可以写(用2.11.4测试):
scala> def f (i: Int, j: Int) = i + j
f: (i: Int, j: Int)Int
scala> val ff = f _
ff: (Int, Int) => Int = <function2>
scala> val p = (3,4)
p: (Int, Int) = (3,4)
scala> ff.tupled(p)
res0: Int = 7
请参阅def tupled: ((T1, T2)) ⇒ R:
创建此函数的tupled版本:而不是2个参数 接受一个scala.Tuple2参数。
答案 2 :(得分:2)
import cv2
import numpy as np
import matplotlib.pyplot as plt
def showing_features(img1, key_points):
plt.imshow(cv2.drawKeypoints(img1, key_points, None))
plt.show()
img1 = cv2.imread('img1.jpg')
img2 = cv2.imread('img2.jpg')
img1_gray = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
img2_gray = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
sift= cv2.xfeatures2d.SIFT_create(nfeatures=0,
nOctaveLayers=3,
contrastThreshold=0.05,
edgeThreshold=10.0,
sigma=1.6)
"*-------------- Create Masks --------------*"
mask1 = np.ones(img1_gray.shape)
#ignore the left half of the first image
mask1[:,:int(mask1.shape[1]/2)] = 0
#ignore the right half of the second image
mask2 = np.ones(img2_gray.shape)
mask2[:,int(mask2.shape[1]/2):] = 0
"*-------------- Change Masks to Uint8 --------------*"
mask1 = mask1.astype(np.uint8)
mask2 = mask2.astype(np.uint8)
"*-------------- Extract SIFT Features --------------*"
kp1m, des1m =sift.detectAndCompute(img1_gray,mask1)
kp2m, des2m =sift.detectAndCompute(img2_gray,mask2)
"*-------------- Display SIFT features after using MASK --------------*"
showing_features(img1, kp1m)
showing_features(img2, kp2m)
答案 3 :(得分:0)
scala> def f (i: Int, j: Int) = i + j
f: (i: Int, j: Int)Int
scala> val p = (3,4)
p: (Int, Int) = (3,4)
scala> val ft = (f _).tupled
ft: ((Int, Int)) => Int = <function1>
scala> ft apply(p)
res0: Int = 7
答案 4 :(得分:0)
在Scala 3中,您可以使用TupledFunction
:
您可以单次使用
summon[TupledFunction[(Int, Int) => Int, ((Int, Int)) => Int]].tupled(f)((2, 3))
要使其易于使用,可以使用扩展名(从Dotty自己的文档中复制)
extension [F, T <: Tuple, R](f: F)(using tf: TupledFunction[F, T => R])
def tupled(t: T): R = tf.tupled(f)(t)
然后您可以执行f.tupled((2, 3))
来获得5
。