Pergunta

Tentando descobrir como obter a raiz quadrada no SML usando este pseudocode:

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

Essas fórmulas nos foram dadas pelo professor, temos que resolver o problema na SML.

Eu tentei algumas maneiras diferentes, mas postarei as diferentes maneiras de erros através do 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>))

As linhas marcadas com um '-' são uma entrada rápida de mim e todos os outros são retornados pelo sistema interativo.

Qualquer ajuda é apreciada, obrigado.

Foi útil?

Solução

@popovitsj tem uma boa inclinação.

O SML usa a correspondência de padrões para determinar qual versão da definição de função usar.

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

É não determinístico e a SML não tem a instalação para voltar atrás e tentar outra definição se a que tenta falhar (ou seja, como o Prolog).

Nesse cenário, você pode apenas usar

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

Essa função é logicamente válida apenas se você estiver passando, um valor que, quando aprovado originalmente, falhará na expressão IF.

Não testei isso, mas acredito que deveria ajudar.

Outras dicas

Talvez isso seja útil? O pseudocódigo implementado em Python:

def sqrt(x,s):
    if (s*s <= x):
        return s
    return sqrt(x,s-1)

Para a SML, não posso verificar isso, porque não tenho um compilador SML, mas talvez isso funcione?

fun sqrt (x, s) = if s*s <= x then s else sqrt(x,s-1)
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top