함수 조합
andThen과 compose를 알아봅니다
함수 조합은(는) CoddyKit의 무료 Scala for Backend Engineering & Functional Programming 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Scala for Backend Engineering & Functional Programming 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
Combining functions
Function composition means building a new function by connecting two existing ones, so the output of one becomes the input of the next. Scala provides andThen and compose for this.
object Main {
def main(args: Array[String]): Unit = {
val addOne = (x: Int) => x + 1
val double = (x: Int) => x * 2
val both = addOne andThen double
println(both(5))
}
}andThen: left to right
f andThen g runs f first, then g. Reading left to right matches the order of execution, which many find intuitive.
(f andThen g)(x) == g(f(x))
object Main {
def main(args: Array[String]): Unit = {
val addOne = (x: Int) => x + 1
val triple = (x: Int) => x * 3
val pipeline = addOne andThen triple
println(pipeline(4)) // (4 + 1) * 3
}
}compose: right to left
f compose g runs g first, then f, the mathematical order f(g(x)).
(f compose g)(x) == f(g(x))
object Main {
def main(args: Array[String]): Unit = {
val addOne = (x: Int) => x + 1
val triple = (x: Int) => x * 3
val pipeline = addOne compose triple
println(pipeline(4)) // (4 * 3) + 1
}
}andThen vs compose
The two are mirror images:
f andThen g=g compose ff compose g=g andThen f
Pick whichever reads more naturally for your situation.
object Main {
def main(args: Array[String]): Unit = {
val f = (x: Int) => x + 10
val g = (x: Int) => x * 2
println((f andThen g)(3))
println((g compose f)(3))
}
}Chaining several functions
You can chain many functions with repeated andThen to build a longer pipeline that flows top to bottom.
object Main {
def main(args: Array[String]): Unit = {
val clean = (s: String) => s.trim
val lower = (s: String) => s.toLowerCase
val bang = (s: String) => s + "!"
val process = clean andThen lower andThen bang
println(process(" HELLO "))
}
}Composition changes types
The composed functions need compatible types: the output type of the first must match the input type of the second. The pipeline can change types along the way.
object Main {
def main(args: Array[String]): Unit = {
val length = (s: String) => s.length
val isLong = (n: Int) => n > 5
val check = length andThen isLong
println(check("scala"))
println(check("functional"))
}
}The identity function
identity returns its input unchanged. It is the neutral element of composition: f andThen identity == f. Useful as a default in folds and conditionals.
object Main {
def main(args: Array[String]): Unit = {
val f = (x: Int) => x * 2
val same = f andThen identity[Int]
println(same(7))
}
}Composing with reduce
Since functions are values, you can store several in a list and compose them all using reduce with andThen.
object Main {
def main(args: Array[String]): Unit = {
val steps: List[Int => Int] = List(_ + 1, _ * 2, _ - 3)
val pipeline = steps.reduce(_ andThen _)
println(pipeline(5)) // ((5+1)*2)-3
}
}Building reusable pipelines
Composition encourages small, single-purpose functions that you assemble into larger behavior, a key idea in functional programming.
object Main {
def main(args: Array[String]): Unit = {
val sanitize = (s: String) => s.trim.toLowerCase
val capitalize = (s: String) => s.capitalize
val format = sanitize andThen capitalize
println(format(" aLiCe "))
}
}Composition with map
A composed function is just a function, so you can pass it straight to map to apply the whole pipeline across a collection.
object Main {
def main(args: Array[String]): Unit = {
val transform = ((x: Int) => x + 1) andThen ((x: Int) => x * x)
println(List(1, 2, 3).map(transform))
}
}Reading composition order carefully
A common bug is confusing andThen and compose. Always remember: andThen = first this, then that; compose = the reverse.
object Main {
def main(args: Array[String]): Unit = {
val inc = (x: Int) => x + 1
val sqr = (x: Int) => x * x
println((inc andThen sqr)(2)) // (2+1)^2 = 9
println((inc compose sqr)(2)) // (2^2)+1 = 5
}
}Quick Check
Given f and g, what does (f andThen g)(x) compute?
Recap
You learned function composition:
f andThen g→g(f(x))(left to right)f compose g→f(g(x))(right to left)- They are mirror images of each other
identityis the neutral element- Compose lists of functions with
reduce(_ andThen _)
자주 묻는 질문
“함수 조합” 강의는 무료인가요?
네 — “함수 조합” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Scala for Backend Engineering & Functional Programming 강의 전체를 잠금 해제할 수 있습니다. Scala for Backend Engineering & Functional Programming 강의에는 총 4개의 강의가 포함되어 있습니다.
“함수 조합”에서 뭘 배우나요?
andThen과 compose를 알아봅니다 브라우저에서 직접 실행하는 실습 코드로 Scala for Backend Engineering & Functional Programming을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Scala for Backend Engineering & Functional Programming을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Scala for Backend Engineering & Functional Programming은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.
“함수 조합” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Scala for Backend Engineering & Functional Programming 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Scala for Backend Engineering & Functional Programming 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.