Skip to content

Instantly share code, notes, and snippets.

@andrewharmellaw
Created March 12, 2020 14:48
Show Gist options
  • Save andrewharmellaw/e54d301d31bf49b1615ac6a4ea830944 to your computer and use it in GitHub Desktop.
Save andrewharmellaw/e54d301d31bf49b1615ac6a4ea830944 to your computer and use it in GitHub Desktop.

Revisions

  1. andrewharmellaw created this gist Mar 12, 2020.
    26 changes: 26 additions & 0 deletions folding.kt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    fun <A, B> foldLeft(l: List<A>,
    seed: B,
    func: (b: B, a: A) -> B) : B {

    return when {
    l.isEmpty() -> seed
    else -> foldLeft(l.tail, func(seed, l.head), func)
    }
    }

    fun <A, B> foldRightOverflows(l: List<A>,
    seed: B,
    func: (a: A, b: B) -> B) : B {

    return when {
    l.isEmpty() -> seed
    else -> func(l.head, foldRightOverflows(l.tail, seed, func))
    }
    }

    fun <T> foldRight(l: List<T>,
    seed: T,
    func: (a: T, b: T) -> T) : T {

    return foldLeft(l.asReversed(), seed, func)
    }