Question

I am new to ML and have been trying simple functions, but I am having trouble trying to get functions to work with real numbers. For example, this reverse function....

    fun reverse (nil) = nil
      | reverse (x::xs) = if xs = nil then [x]
                         else (reverse xs) @ [x];

I get the propper output for integers and strings.

    - reverse [1,2,3,4];
    val it = [4,3,2,1] : int list
    - reverse ["a" , "b" , "c" , "d" ];
    val it = ["d","c","b","a"] : string list

Can anyone explain to me why this function will not work with real numbers?

Here is the output when I try reals...

    - reverse [1.0, 2.0];
    stdIn:1.2-53.9 Error: operator and operand don't agree [equality type required]
      operator domain: ''Z list
      operand:         real list
      in expression:
        reverse (1.0 :: 2.0 :: nil)
Was it helpful?

Solution

real is not an equality type in ML, and so neither are polymorphic types constructed from reals -- in particular, real lists are not equality types, and so you cannot use the operator = to compare two real lists, even if those lists are empty. Instead, you need to pattern match. For example,

fun reverse [] = []
  | reverse (x::xs) = (reverse xs) @ [x]

or

fun reverse [] = []
  | reverse (x::xs) = case xs of
                           [] => [x]
                         | _ => (reverse xs) @ [x]

will work even for nonequality types.

(Alternately, use the built in function List.rev.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top