Pregunta

I'm learning pattern matching in SML and I want to write a function fact_till (a,b) to calculate a!/b!. So for example, fact_till(5,3) should return 5*4=20.

My code looks like this:

fun fact_till t = case t of
                  (a,a) => 1
                | (a,b) => a * fact_till(a-1,b)

But I got Error: duplicate variable in pattern(s): a. I presume SML does not recognize the pattern (a,a). Then what's the correct way of expressing this pattern?

¿Fue útil?

Solución

The correct way to do this is:

fun fact_till (a,b) = if a = b
                      then 1
                      else a * fact_till(a - 1, b)

This can also be done with a case statement, if you wish:

fun fact_till (a,b) = case a = b of
                      true => 1
                    | false => a * fact_till(a - 1, b)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top