Rob Hoelz <hoelz@[EMAIL PROTECTED]
> writes:
> I won't lie; this is for a homework assignment, but I'm not asking it
> to be done for me; I just want to know how to accomplish destructive
> assingment in ML. The problem is to construct a function with
> memoization, so here's what I have:
>
> local
> val memory = []
> in
> fun fastF 0 = 1 |
> fastF ~1 = 0 |
> fastF ~2 = 0 |
> fastF ~3 = 0 |
> fastF m =
> let
> val result = find (fn (key, value) => key = m) memory
> in
> if isSome result then
> #2(result)
> else
> let
> val result = fastF(m-1) + fastF(m-2) + fastF(m-3) -
> fastF(m-4)
> in
> ((val memory = ((m, result) :: memory)); result)
> end
> end
>
> Unfortunately, (val memory = ...) doesn't accomplish what I need; it
> causes a syntax error. Could somone shed some light on how I could
> assign to memory? Thanks!
Variables in SML can't be destructively assigned to, so the third-last
line just creates a new local variable called memory.
But SML has references that can be overwritten. Note that when you
have a variable that holds a reference value, it is not the variable
that is overwritten, but the reference value that it holds.
So, start your program with "val memory = ref []". Use "!memory" when
looking up the value of the reference and "memory := ..." to assign to
it.
Torben


|