Scientific Calculator

(public) silentmatt/functional

By silentmatt Matthew Crumley

Useful functions for doing functional programming, and list processing

Tagged: functional list

// Combine multiple lists into a list of lists, containing the corresponding element from each input
var zip = function() {
    var length = apply(min, map(:len, @) or [0]);
    var res = [];
    for i in (0..length) -> push(res, map(a -> a[i], @));
    res;
};

// Combine multiple lists into a single list, containing the result of calling function f with the corresponding element from each input
var zipWith = function(f) {
    @ = @[1..len @];
    var length = apply(min, map(:len, @) or [0]);
    var res = [];
    for i in (0..length) -> push(res, apply(f, map(a -> a[i], @)));
    res;
};

var withIndex = (list) -> zip(range(len list), list);

var head = list -> list[0];
var tail = list -> list[1..len list];

// Partial function application: papply(f, 1, 2)(3) == f(1, 2, 3)
var papply = function(f) {
    var args = slice(@, 1);
    function() {
        apply(f, concat(args, @))
    }
};

spam? | offensive?

0 Comments

Sign in to leave a comment