반응형
스칼라 : 함수 인수에서 튜플 분해
파이썬에서는 다음과 같이 할 수 있습니다.
def f((a, b)):
return a + b
d = (1, 2)
f(d)
여기서 전달 된 튜플은에 전달되는 동안 분해됩니다 f
.
지금 스칼라에서 나는 이것을하고 있습니다.
def f(ab:(Int, Int)) : Int = {
val (a, b) = ab
a + b
}
val d = (1, 2)
f(d)
인수가 전달되는 동안 분해가 발생하도록 여기서 할 수있는 일이 있습니까? 그냥 궁금해.
감사.
함수를 만들고 입력을 패턴 일치와 일치시킬 수 있습니다.
scala> val f: ((Int, Int)) => Int = { case (a,b) => a+b }
f: ((Int, Int)) => Int
scala> f(1, 2)
res0: Int = 3
또는 메소드 입력을 match
키워드 와 일치 시키십시오 .
scala> def f(ab: (Int, Int)): Int = ab match { case (a,b) => a+b }
f: (ab: (Int, Int))Int
scala> f(1, 2)
res1: Int = 3
또 다른 방법은 두 개의 인수가있는 함수를 사용하여 "튜플"하는 것입니다.
scala> val f: (Int, Int) => Int = _+_
f: (Int, Int) => Int = <function2>
scala> val g = f.tupled // or Function.tupled(f)
g: ((Int, Int)) => Int = <function1>
scala> g(1, 2)
res10: Int = 3
// or with a method
scala> def f(a: Int, b: Int): Int = a+b
f: (a: Int, b: Int)Int
scala> val g = (f _).tupled // or Function.tupled(f _)
g: ((Int, Int)) => Int = <function1>
scala> g(1, 2)
res11: Int = 3
// or inlined
scala> val f: ((Int,Int)) => Int = Function.tupled(_+_)
f: ((Int, Int)) => Int = <function1>
scala> f(1, 2)
res12: Int = 3
object RandomExperiments extends App{
def takeTuple(t:(Int,Int))=print (s"$t ${t._1}\n")
takeTuple(1,3)
takeTuple((1,3))
takeTuple(((1,3)))
}
인쇄물:
(1,3) 1
(1,3) 1
(1,3) 1
참조 URL : https://stackoverflow.com/questions/11615656/scala-decomposing-tuples-in-function-arguments
반응형
'program story' 카테고리의 다른 글
Python Pandas로 들어오는 실시간 데이터를 처리하는 방법 (0) | 2020.12.26 |
---|---|
git-subtree 추가 후 rebase하는 방법은 무엇입니까? (0) | 2020.12.26 |
GreenDAO 스키마 업데이트 및 데이터 마이그레이션? (0) | 2020.12.25 |
Android Studio, 에뮬레이터 실행시 갑자기 GPU 드라이버 문제 발생 (0) | 2020.12.25 |
두 개의 Subversion 저장소를 동기화하는 방법은 무엇입니까? (0) | 2020.12.25 |