x:xs , where x is the beginning of the list ( head ), xs is the continuation ( tail ).
nil is an empty list, prepend ( cons ) is the insert function at the beginning of the list, head and tail . prepend('a', prepend('b', nil)) // 'a' -> 'b' -> nil prepend function: function prepend(x, xs) { return function (select) { return select(x, xs) } } select function is needed to access free variables ( x:xs ).head and tail is reduced to calling the list function with the desired select value: function select_head(x, xs) { return x } function select_tail(x, xs) { return xs } function head(a) { return a(select_head) } function tail(a) { return a(select_tail) } nil ): function nil() { return nil } head(nil) === tail(nil) === nil . var a = prepend('a', prepend('b', nil)) // 'a' -> 'b' -> nil head(a) // => 'a' head(tail(a)) // => 'b' head(tail(tail(a))) // => nil while (a !== nil) { console.log(head(a)) a = tail(a) } map : function map(fn, a) { if (a === nil) return nil return prepend(fn(head(a)), map(fn, tail(a))) } var a = prepend(1, prepend(2, prepend(3, nil))) // 1 -> 2 -> 3 -> nil function power_of_2(x) { return 1 << x } var b = map(power_of_2, a) // 2 -> 4 -> 8 -> nil filter , reduce ) are offered to the reader as homework.
Source: https://habr.com/ru/post/175725/
All Articles