Skip to content
Mario Arias edited this page Sep 17, 2015 · 5 revisions

The top-level function constant receive a parameter and returns a function that always return the original parameter. (i.e. K in SKI combinator calculus)

import org.funktionale.utils.*

private val add5 = {(i: Int) -> i + 5 }
private val multiplyBy2 = {(i: Int)-> i * 2 }

private fun applyTwoFunctions(i: Int, firstFunction: (Int) -> Int, secondFunction: (Int) -> Int): Int {
  val x = firstFunction(i)
  return secondFunction(x)
}

@Test fun testConstant() {

  assertEquals(applyTwoFunctions(2, add5, constant(1)), 1) //always return 1

  val list = arrayListOf("foo", "bar", "baz")

  val to7: (String) -> Int = constant(7) // Transform any String to an int of value 7
        
  assertEquals(list.map(to7), arrayListOf(7, 7, 7))
}

Clone this wiki locally