Skip to content

Instantly share code, notes, and snippets.

@ice1000
Created May 2, 2017 16:14
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ice1000/c024efa6d46ef63111c95dee139a83e7 to your computer and use it in GitHub Desktop.
Save ice1000/c024efa6d46ef63111c95dee139a83e7 to your computer and use it in GitHub Desktop.
Kotlin can also write recursive lambda
package main
/**
* Created by ice1000 on 2017/5/2.
*
* @author ice1000
*/
fun main(args: Array<String>) {
fun lambda(it: Int): Int =
if (it <= 2) 1 else lambda(it - 1) + lambda(it - 2)
(1..10)
.map(::lambda)
.forEach(::println)
var lambda2: (Int) -> Int = { it }
lambda2 = { if (it <= 2) 1 else lambda(it - 1) + lambda(it - 2) }
(1..10)
.map(lambda2)
.forEach(::println)
}
@tobia
Copy link

tobia commented Apr 15, 2020

Your lambda2 is not recursive, it calls lambda by mistake.

You can make it recursive using lateinit:

lateinit var lambda2: (Int) -> Int
lambda2 = { if (it <= 2) 1 else lambda2(it - 1) + lambda2(it - 2) }

@ice1000
Copy link
Author

ice1000 commented Apr 16, 2020

Oh, it was written long ago and there weren't local lateinit back then. Thanks for the suggestion!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment