Example source code for functional programming in Kotlin
funfunstory / fp-kotlin-example Goto Github PK
View Code? Open in Web Editor NEWExample source code for functional programming in Kotlin
License: MIT License
Example source code for functional programming in Kotlin
License: MIT License
4-1. orElse
함수는 PartialFunction
의 입력값 p
가 조건에 맞으면 PartialFunction
을 그대로(this) 반환하고 조건에 맞지 않으면 that
을 반환한다.
문제 대로라면 (that조건과 관계 없이) p 조건만 맞지 않을 경우 that을 반환해야 한다고 이해를 했습니다.
그런데 solution에는 p조건과 that조건을 모두 체크하고 둘다 맞지 않는 경우 exception처리를 하고 있습니다.
문제 내용대로라면 아래와 같이 수정이 되어야하지 않을까요?
fun main() {
val cond1: (Int) -> Boolean = { it in 1..3 }
val body1: (Int) -> String = {
when (it) {
1 -> "one"
2 -> "two"
3 -> "three"
else -> throw IllegalArgumentException("THIS IS DEFAULT CATCHER")
}
};
val cond2: (Int) -> Boolean = { it in 3..6 }
val body2: (Int) -> String = { "wow $it" }
val oneToThree = PartialFunction(cond1, body1); //1~3
val threeToSix = PartialFunction(cond2, body2); //3~6
val test2 = threeToSix.orElse(oneToThree)(3);
require(test2 == "wow 3")
val test3 = threeToSix.orElse(oneToThree)(1);
require(test3 == "one")
try {
val test = threeToSix.orElse(oneToThree)(50);
} catch (err: Throwable) {
require(err.message == "THIS IS DEFAULT CATCHER")
}
}
class PartialFunction<P, R>(
private val condition: (P) -> Boolean,
private val f: (P) -> R
) : (P) -> R {
override fun invoke(p: P): R = when {
condition(p) -> f(p)
else -> throw IllegalArgumentException("$p isn't supported.")
}
fun isDefinedAt(p: P): Boolean = condition(p)
fun orElse(that: PartialFunction<P, R>): PartialFunction<P, R> =
PartialFunction({ true },
{
if (this.isDefinedAt(it))
f(it)
else
that.f(it)
})
}
6장에 믹스인 예제추가.
~ 7-15
확인된 이슈 편하게 올려도 될까요?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.