복붙노트

[SCALA] 어떻게 튜플에 함수를 적용?

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!

사전에 많은 감사.

해결법

  1. ==============================

    1.스칼라 2.7 :

    스칼라 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>
    

    스칼라 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>
    
  2. ==============================

    2.다른 대답에 최대에 따라, 하나는 (2.11.4 테스트) 쓸 수 있습니다 :

    다른 대답에 최대에 따라, 하나는 (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 :

  3. ==============================

    3.

    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. from https://stackoverflow.com/questions/1987820/how-to-apply-a-function-to-a-tuple by cc-by-sa and MIT license