Pergunta

I want to find the first occurence of a digit in a list :

let pos_list = function (list , x) -> 
   let rec pos = function 
    |([] , x , i) -> i
    |([y] , x , i) -> if y == x then i
    |(s::t , x , i) -> if s == x then i else pos(t , x , i + 1) in pos(list , x ,  0) ;;

but the compiler complain that the expression is a "uint" type , and was used instead with a "int" type .

Foi útil?

Solução

Remove the second case from the pattern matching. This case is already matched by the last one with s = y, t = []. So the function can be simplified to

let pos_list (list, x) =
    let rec pos = function 
    | ([], x, i) -> i
    | (s::t, x, i) -> if s == x then i else pos(t, x, i + 1) in pos(list, x, 0) ;;

Outras dicas

Why are you using == (physical equality) instead = which is structural equality? I realize that this might not make a difference if you only have integers but it might yield unexpected behaviour down the road.

See the Comparisons section in the doc: http://caml.inria.fr/pub/docs/manual-ocaml/libref/Pervasives.html

Pavel Zaichenkov's answer is of course the best one, but you might be interested in knowing the exact cause of the error. Namely, when you have

if y == x then i

without a corresponding else expression, the whole expression is treated as

if y == x then i else ()

where () is the only value of the type unit (and not uint), which is the type of expressions that are evaluated for their side effects only. Since both branches of the if must have the same type, i is deemed to have type unit also. Then, when type-checking the third branch of the pattern-matching, you try to add i and 1, which means that i should have type int, hence the type error.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top