Created
November 29, 2017 13:43
-
-
Save rsp/ffd9473bb1571d1297091864f0c49a54 to your computer and use it in GitHub Desktop.
inFullMobile Language Wars: Round 1 - Kotlin Solution 1 - full code by @rainqer - See: https://gist.github.com/rsp/d8bdbafa09f24f99eebc8ed60fe205c8
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.infullmobile.languagewars | |
import org.junit.Assert.assertEquals | |
import org.junit.Test | |
class ExampleUnitTest { | |
@Test | |
fun testHelperFunctions() { | |
assertEquals(applyXZeroTimes(increment)(0), 0) | |
assertEquals(applyXOnce(increment)(0), 1) | |
assertEquals(applyXTwice(increment)(0), 2) | |
assertEquals(applyXThousandfold(increment)(0), 1000) | |
} | |
@Test | |
fun testApplyingOneTimeLess() { | |
assertEquals(f(applyXZeroTimes)(increment)(0), 0) | |
assertEquals(f(applyXOnce)(increment)(0), 0) | |
assertEquals(f(applyXTwice)(increment)(0), 1) | |
assertEquals(f(applyXThousandfold)(increment)(0), 999) | |
} | |
} | |
// x = method to be applied | |
// a = method duplicating x n times | |
// b = method duplicating x n-1 times | |
// f = method taking a returning b | |
val applyXZeroTimes: ((Int) -> Int) -> (Int) -> Int = { x -> { input -> input } } | |
val applyXOnce: ((Int) -> Int) -> (Int) -> Int = { x -> x } | |
val applyXTwice: ((Int) -> Int) -> (Int) -> Int = { x -> applyXTwice(x) } | |
fun applyXTwice(x: (Int) -> Int): (Int) -> Int = { input -> x(x(input)) } | |
val applyXThousandfold: ((Int) -> Int) -> (Int) -> Int = { x -> applyXTenfold(applyXTenfold(applyXTenfold(x))) } | |
fun applyXTenfold(x: (Int) -> Int): (Int) -> Int = { input -> x(x(x(x(x(x(x(x(x(x(input)))))))))) } | |
fun f(a: ((Int) -> Int) -> ((Int) -> Int)): ((Int) -> Int) -> (Int) -> Int { | |
val invocationCount = a(increment)(0) | |
return if (invocationCount > 0) { x: (Int) -> Int -> { input -> applyXTimes(x, invocationCount - 1)(input) } } | |
else { _ -> { input -> input } } | |
} | |
fun applyXTimes(x: (Int) -> Int, count: Int): (Int) -> Int | |
= { argument -> (1..count).fold(argument, { acc, _ -> x(acc) }) } | |
val increment: (Int) -> Int = { counter -> counter + 1 } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment