Last active
October 20, 2020 19:50
-
-
Save SpandanBG/c2cf6a08703be3c716e963c0048997ef to your computer and use it in GitHub Desktop.
Challenge 1 from https://bartoszmilewski.com/2014/11/24/types-and-functions/ => A memoize function takes a function f and returns a function that takes a value x. When x is passed the first time it returns a function that would take the next x. If the x passed was passed before it would compute f(x) and return the result. The solution here is do…
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const head = x => _ => x; | |
const tail = _ => y => y; | |
const arr = x => xs => f => f(x)(xs); | |
const none = () => null; | |
const memorize = f => { | |
const bind = xs => _x => y => { | |
if (xs === none) { | |
return bind(arr({arg: y, ret: f(y)})(_x))(none); | |
} | |
if (xs(head).arg === y) { | |
return xs(head).ret; | |
} | |
return bind(xs(tail))(arr(xs(head))(_x))(y); | |
}; | |
return bind(none)(none); | |
}; | |
const fib = n => { | |
if (n <= 0) { | |
return 1; | |
} | |
return n * fib(n - 1); | |
}; | |
((/* main */) => { | |
let memid = memorize(fib); | |
memid = memid(3); | |
memid = memid(4); | |
memid = memid(1); | |
memid = memid(2); | |
console.log(memid(4)) | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment