Question

I am trying to compute binomial coefficients using Dynamic Programming. I keep getting this error

fun binomial(m:int, n:int, DP) =
if n = m orelse n = 0 then 
    Array2.update(DP, m, n, 1)
else if Array2.sub(DP, m, n) = ~1 then ( 
    if Array2.sub(DP, m-1, n) = ~1 then
        Array2.update(DP, m-1, n, binomial(m-1, n, DP))
    else 
        Array2.update(DP, m-1, n, Array2.sub(DP, m-1, n));
    if Array2.sub(DP, m-1, n-1) = ~1 then
        Array2.update(DP, m-1, n-1, binomial(m-1, n-1, DP))
    else
        Array2.update(DP, m-1, n-1, Array2.sub(DP, m-1, n-1));
    let
        val k = Array2.sub(DP, m-1, n) + Array2.sub(DP, m-1, n-1);
    in
        Array2.update(DP, m, n, k)
    end
)
else
    Array2.update(DP, m, n, Array2.sub(DP, m, n));
Array2.sub(DP, m, n)

I am don't understand what this error is trying to say.

6.5-25.48 Error: right-hand-side of clause doesn't agree with function result type     [literal]
expression:  unit
result type:  int
in declaration:
binomial =
  (fn (<pat> : int,<pat> : int,DP) =>
        if <exp> orelse <exp>
        then Array2.update <exp>
        else if <exp> then <exp> else <exp>)

Can anyone help me?

Was it helpful?

Solution

Your function binomial returns the result of Array2.update, which is a unit. But you're passing this return value in to Array2.update as the last argument, which is expecting an int.

EDIT: Oh, now I see... Your only problem is that the last line (Array2.sub(DP,m,n)) isn't part of your function - if you want to build a list of expressions, you need to surround it with brackets. So instead of

fun binomial (m,n,DP) = <update logic>; Array2.sub(DP,m,n)

you want

fun binomial (m,n,DP) = (<update logic>; Array2.sub(DP,m,n))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top