Identity and constant

Identity and constant are straightforward functions. The identity function returns the same value provided as parameter; similar to additive and multiplicative identity property, adding 0 to any number is still the same number.

The constant<T, R>(t: T) function returns a new function that will always return the t value:

fun main(args: Array<String>) {

val oneToFour = 1..4

println("With identity: ${oneToFour.map(::identity).joinToString()}") //1, 2, 3, 4

println("With constant: ${oneToFour.map(constant(1)).joinToString()}") //1, 1, 1, 1

}

We can rewrite our fizzBuzz value using constant:

fun main(args: Array<String>) {
val fizz = PartialFunction({ n: Int -> n % 3 == 0 }, constant("FIZZ"))
val buzz = PartialFunction({ n: Int -> n % 5 == 0 }, constant("BUZZ"))
val fizzBuzz = PartialFunction({ n: Int -> fizz.isDefinedAt(n) && buzz.isDefinedAt(n) }, constant("FIZZBUZZ"))
val pass = PartialFunction<Int, String>(constant(true)) { n -> n.toString() }

(1..50).map(fizzBuzz orElse buzz orElse fizz orElse pass).forEach(::println)
}

Identity and constant functions are useful in functional programming or in implementations of math algorithms, for example, constant is K in SKI combinator calculus.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.133.156.251