Search code examples
mlinfix-notation

Compound function in ML


I need to write a function compound in ML that will behave as follows:

Compound takes in a bin op f, and an int n, and a value x, and it applies the operator to x N times. Here is an example:

compound f 0 x = x
compound f 1 x = x f x

I am a newbie at ML so I have trouble understanding how to write this function. I will greatly appreciate any help!


Solution

  • You have to write a function that is simplified version of foldl or foldr, depending on f associativity. But, since you missed parenthesis in your examples, I suppose f is right associative.

    The code will be for your foldr case:

    fun compound f x 0 = x
      | compound f x n = f(x, compound f x (n-1));