OCaml Question 7

Question 7
A baby tries to say “memorization”
1. (10 points)
The players of your game have been complaining for weeks that it is too slow. After profilins the game, you notice that there are many calls to the same function with the same inputs. However, you aren’t entirely sure why, and you need to fix this bug yesterday or it will reflect poorly on your annual review.
You decide to use memoization. This is a technique in which we essentially cache the results of a unction call, so that we can later look up the cached result instead of recalculating it. Even though you cannot pinpoint the cause of the slowdown, you are nonetheless a good programmer, so you decide to make a general memoization function.
You will implement the function memo: (‘a -› ‘b) -› (‘a -> ‘b), such that memo f returns a function g that is equivalent to f – it returns the same outputs for the same inputs – but such that g x looks up its input x in a cache before falling back to calling g x to calculate the result.
Of course, this result is then stored in the cache so that subsequent calls g x can immediately retrieve the result instead of recalculating it.
To implement the cache, you will use an (‘a * ‘b) list ref to store a mutable list of key- value pairs. Complete the implementation of memo below. To look up an item in the cache, you can use the function :
List. assoc opt: ‘a -> (‘a * ‘b) list -> ‘b option.
Question 7 1
Programming Help, Add QQ: 749389476
let memo (f : ‘a -> ‘b) : ‘a -> ‘b =
let cache : (‘a * ‘b) list ref = ref [] in
Question 7 2
浙大学霸代写 加微信 cstutorcs