smlsmlnjlow-levelsqrt

Trying to get square root in SML?


Trying to work out how to get the square root in SML using this pseudocode:

sqrt x s = s if s*s <= x
sqrt x s = sqrt x (s-1) if s*s > x

This formulae was given to us by the lecturer, we have to solve the problem in SML.

I've tried it a few different ways, but I'll post the different ways with the errors via the console:

- fun sqrt x s = if ((s*s) <= x) then s | sqrt x s = if (s*s) > x then sqrt x (s - 1);
stdIn:32.39-32.45 Error: syntax error: deleting  BAR ID
stdIn:32.52-32.56 Error: syntax error: deleting  IF LPAREN
stdIn:32.59-32.62 Error: syntax error: deleting  RPAREN ID
stdIn:32.65-32.74 Error: syntax error: deleting  THEN ID
- fun sqrt x s = s if ((s*s) <= x) | sqrt x (s - 1);
stdIn:10.2-17.4 Error: syntax error: deleting  IF LPAREN
stdIn:17.14 Error: syntax error found at RPAREN
- fun sqrt x s = s if s*s <= x | sqrt x (s - 1);
stdIn:10.2-17.4 Error: syntax error: deleting  IF ID
- fun sqroot x s = s if s*s <= x | sqrt x (s - 1);
stdIn:17.2-17.6 Error: syntax error: deleting  IF ID
- fun sqrt x s = s IF s*s <= x | sqrt x (s - 1);
= ;
= ;
= ;;
stdIn:17.28-34.2 Error: syntax error: deleting  SEMICOLON SEMICOLON SEMICOLON
- fun sqrt x s = s IF s*s <= x END | sqrt x s = sqrt x (s-1) IF s*s > x END;
stdIn:17.12-17.15 Error: unbound variable or constructor: END
stdIn:10.2-17.2 Error: unbound variable or constructor: IF
stdIn:35.20-35.23 Error: unbound variable or constructor: END
stdIn:35.9-35.11 Error: unbound variable or constructor: IF
stdIn:1.17-17.15 Error: operator is not a function [circularity]
  operator: 'Z
  in expression:
    (s <errorvar>) s
stdIn:1.17-17.15 Error: operator and operand don't agree [overload]
  operator domain: 'Z * 'Z
  operand:         _ * (_ -> 'Y)
  in expression:
    (s <errorvar>) s * s
stdIn:1.6-35.23 Error: types of rules don't agree [literal]
  earlier rule(s): (_ -> int) * (_ -> 'Z) -> bool
  this rule: (_ -> int) * int -> bool
  in rule:
    (x,s) => (<exp> <exp>) s * s > x <errorvar>
stdIn:1.6-35.23 Error: right-hand-side of clause doesn't agree with function result type [literal]
  expression:  (_ -> 'Z) -> bool
  result type:  int -> _ -> int -> int
  in declaration:
    sqrt = (fn arg => (fn <pat> => <exp>))

Lines marked with a '-' are prompt input from me and all others are returned by the interactive system.


Solution

  • SML uses pattern matching to determine which version of the function definition to use.

    fun sqrt x s = if ((s*s) <= x) then s | sqrt x s = if (s*s) > x then sqrt x (s - 1);
    

    Is non-deterministic, and SML doesn't have the facility to backtrack and try another definition if the one it tries fails (i.e. like Prolog).

    In this scenario you can just use

    fun sqrt x s = if s * s <= x then s else sqrt x (s-1);
    

    This function is logically valid only if you are passing it a value that when originally passed will fail the if expression.

    I haven't tested this but I believe it should help.