Code Monkey home page Code Monkey logo

kons's Introduction

Kons

Download

Kotlin linked list implementation using lazily evaluated cons cells.

Gradle

repositories {
    maven { url "https://dl.bintray.com/aedans/maven/" }
}

dependencies {
    compile 'io.github.aedans:kons:$kons_version'
}

Code Samples

// Recursively folds a list
tailrec fun <A, R> Cons<A>.fold(r: R, fn: (R, A) -> R): R = when (this) {
    Nil -> r
    is Cell -> cdr.fold(fn(r, car), fn) // car and cdr are smart cast from nullable to non-nullable
}

// Lazily filters a list
tailrec fun <T> Cons<T>.filter(fn: (T) -> Boolean): Cons<T> = when (this) {
    Nil -> Nil
    is Cell -> if (fn(car)) lazyCar cons later { cdr.filter(fn) } else cdr.filter(fn)
}

// Stack safe due to Eval
fun <A, B> Cons<A>.map(fn: (A) -> B): Eval<Cons<B>> = when (this) {
    Nil -> Eval.Nil
    is Cell -> now(later { fn(car) } cons defer { cdr.map(fn) })
}

// List of all natural numbers
val nat = generateSequence(0) { it + 1 }.toCons()

// List of all positive even numbers
val evens = nat.map { it * 2 }

// List of all primes
val primes = nat.filter { i -> (2 until i).none { i % it == 0 } }

kons's People

Contributors

aedans avatar

Stargazers

 avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

Forkers

rhurkes

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.