Skip to content

Instantly share code, notes, and snippets.

@abiodun0
Last active January 27, 2023 23:22
Show Gist options
  • Save abiodun0/10d24969af3e45e246c106184fa52d88 to your computer and use it in GitHub Desktop.
Save abiodun0/10d24969af3e45e246c106184fa52d88 to your computer and use it in GitHub Desktop.
For next blog post con cdr car
const cons = (x, y) => (m) => m(x, y)
const car = (z) => z((p, q) => p)
const cdr = (z) => z((p, q) => q)
const someLinkedList = cons(1, cons(2, cons(3 , null)))
// iterating
const each = (func, list) => {
if(list) {
element = car(list)
func(element)
each(func, cdr(list))
}
}
// each(console.log, someLinkedList)
// let [head, ...tail] = [1,2,3,4,5]
const convertToLinkedList = (array) => {
if(!array.length) {
return null
}
const [head, ...tail] = array;
return cons(head, convertToLinkedList(tail))
}
sampleLinked = convertToLinkedList([1,2,3,4,5])
each(console.log, sampleLinked)
convertToArray = (linked, array=[]) => {
if(linked) {
const element = car(linked)
const rest = cdr(linked)
return convertToArray(rest, array.concat(element))
}
return array;
}
convertToArray(sampleLinked)
cons = ->(x, y=nil) {
->(m){ m.(x, y) }
}
car = -> (z){
z.(->(p,q=nil) {p})
}
cdr = -> (z){
z.(->(p,q=nil) {q})
}
cons = ->(x, y=nil) {
->(m){ m.(x, y) }
}
car = -> (z){
z.(->(p,q=nil) {p})
}
cdr = -> (z){
z.(->(p,q=nil) {q})
}
convertToArray = ->(consz) {
if !consz.respond_to? :call
return []
end
return [car.(consz)] + convertToArray.(cdr.(consz))
}
covertToLinkedList = ->(array) {
if array.size == 0
return nil
end
head, *tail = array
return cons.(head, covertToLinkedList.(tail))
}
linkList = covertToLinkedList.([1,5,6,7,9])
# cons(1, cons(2, cons(3, cons(4, null))))
# convertToArray.(cons.(1, cons.(1, cons.(4))))
# [car.(list)] + cdr.(list)
# head = ->(x) {
# head, *tail = x
# head
# }
# cons = ->(x, y) {
# [*y, x]
# }
reduceRight = ->(xs, acc, &f) {
id = ->(x) {x}
reduceResult = xs.reduce(id) {|accf, n| ->(z){
accf.(f.(z,n))
} }
reduceResult.(acc)
} #=> 151200
reduceRight.([1,2,4], []) {|n, x| n.push(x)
n
}
map = ->(x, &f) {
x.reduce([]) {|acc, n| cons.(f.(n), acc) }
} #=> 151200
convertToArray.(map.([1, 5, 7, 19]) { |n| n * n})
class Array
def reduceRight(acc, &f)
id = ->(x) {x}
reduceResult = self.reduce(id) {|accf, n| ->(z){
accf.(f.(z,n))
} }
reduceResult.(acc)
end
end
# convertToArray.(map.([1, 5, 7, 19]) { |n| n * n})
[1,2,4].reduceRight([]) {|n, x| n.push(x)
n
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment