Skip to content

Instantly share code, notes, and snippets.

@kana-sama
Created March 10, 2017 00:29
Show Gist options
  • Save kana-sama/a96fd2ecc3c0073ef59dcbf39486bd79 to your computer and use it in GitHub Desktop.
Save kana-sama/a96fd2ecc3c0073ef59dcbf39486bd79 to your computer and use it in GitHub Desktop.
lambda-cons-lists
// тест-фреймворк
function describe(groupName, block) {
let index = 0
function assert(a) {
return {
equals(b) {
index += 1
const testName = `${ groupName }.${ index }`
if (a == b) {
console.log(`${ testName } ok.`)
} else {
console.log(`${ testName } error.`)
console.log(`Expected: ${ b }`)
console.log(`Result: ${ a }`)
}
}
}
}
block(assert)
}
//// пара
const pair =
x => y => f =>
f(x)(y)
const first =
p =>
p(x => y => x)
const second =
p =>
p(x => y => y)
// тесты
describe("pair", assert => {
const oneAndTwo = pair(1)(2)
assert(first(oneAndTwo)).equals(1)
assert(second(oneAndTwo)).equals(2)
})
//// списки
// создание пустого списка
const nil =
f => n =>
n
// создание списка с элементом и хвостом
const cons =
value => next => f => n =>
f(value)(next(f)(n))
// определяет, пуст ли список
const empty =
list =>
list(_ => _ => false)(true)
// сумма чисел
const sum =
list =>
list(x => acc => x + acc)(0)
// применение
const map =
f => list =>
list(x => acc => cons(f(x))(acc))(nil)
const filter =
f => list =>
list(x => acc => f(x) ? cons(x)(acc) : acc)(nil)
// сложение
const concat =
other => list =>
list(x => acc => cons(x)(acc))(other)
// тесты
describe("list", assert => {
// преобразовать в строку, для вывода
const show =
list =>
list(x => acc => [x, ...acc])([]).join(", ")
const example =
cons(1)(cons(2)(cons(3)(nil)))
const succ =
x =>
x + 1
const odd =
x =>
x % 2 == 1
assert(show(example)).equals("1, 2, 3")
assert(sum(example)).equals(6)
assert(show(map(succ)(example))).equals("2, 3, 4")
assert(show(concat(example)(example))).equals("1, 2, 3, 1, 2, 3")
assert(show(filter(odd)(example))).equals("1, 3")
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment