Skip to content

Instantly share code, notes, and snippets.

@bennettmcelwee
Last active March 12, 2019 05:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bennettmcelwee/25c65ee0b1b4bf3b65fcc916b91051c3 to your computer and use it in GitHub Desktop.
Save bennettmcelwee/25c65ee0b1b4bf3b65fcc916b91051c3 to your computer and use it in GitHub Desktop.
var digitToNum = digit => ({v:digit, f:`${digit}`})
var partitions = x => times(i => [take(i+1, x), drop(i+1, x)], x.length - 1)
const negop = {o:(a) => ({o:negop, a, v:-a.v, f:`-${a.f}`})}
const unops = [negop]
const addop = {o:curry((a,b) => ({o:addop, a, b, v:a.v+b.v, f:`${a.f}+${b.f}`}))}
const subop = {o:curry((a,b) => ({o:subop, a, b, v:a.v-b.v, f:`${a.f}-${b.f}`}))}
const mulop = {o:curry((a,b) => ({o:mulop, a, b, v:a.v*b.v, f:`${a.f}x${b.f}`}))}
const divop = {o:curry((a,b) => (b.v != 0 ? {o:divop, a, b, v:a.v/b.v, f:`${a.f}/${b.f}`} : null))}
const biops = [addop, subop, mulop, divop]
var applyOps = (ops) => (...nums) => map(op => apply(op.o)(nums))(ops)
function nums(digits) {
if (digits.length === 1) {
const num = digitToNum(digits[0])
return append(num, applyOps(unops)(num))
} else {
return flatten(
map(
compose(
map(apply(applyOps(biops))),
apply(xprod),
map(nums)
))(
partitions(digits)
)
)
}
}
function nums2(digits) {
console.log('nums2', digits)
if (digits.length === 1) {
const num = digitToNum(digits[0])
return [num]//append(num, applyOps(unops)(num))
} else {
const lastDigit = last(digits)
const prevs = nums2(dropLast(1)(digits))
const r = map(
addDigit(lastDigit),
prevs
)
logNums(r)
return r
}
}
const addDigit = curry((digit, num) => {
console.log('addDigit', digit, num)
return (num.b !== undefined) ?
map(num.o.o(num.a))(addDigit(digit, num.b)) :
applyOps(biops)(num.a || num, digitToNum(digit))
}
)
var two = digitToNum(2)
var three = digitToNum(3)
//logNums(nums([1,2,3]))
const nn = nums([1,2,3])
nn[11].f
//addDigit(4, nn[11])
//logNums(addDigit(4, nn[11]))
var digits = [1,2,3]
logNums(nums2(digits))
//nums2(digits)
/*
var three = digitToNum(3)
var seven = digitToNum(7)
applyOps(unops)(three)
applyOps(biops)(three, seven)
*/
/*
sortBy(prop('0'))(
map(([k,v]) => [v[0].v, map(prop('f'))(v)])(
toPairs(groupBy(prop('v'))(nums(digits)))
))
.forEach(x=>console.log(x))
*/
function groupNums(nums) {
return map(([k,v]) => [v[0].v, map(prop('f'))(v)])(
toPairs(groupBy(prop('v'))(nums))
)
}
function logNums(nums) {
return nums
compose(
forEach(([k, v])=>console.log(`${k}: ${v}`)),
sortBy(prop('0')),
filter(([k, v]) => Number.isInteger(k) && k>0),
groupNums
)(nums)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment