0
votes

I want to find the max element in a int list. The idea is to call find_max only once and let support do the dirty job. The function support returns an int, the first value is 0 then when a new max is found it's value is saved, added to the result ,the previous max is changed and it's value deducted from the result.

This because :

old_max = x
result = 0 + old_max

A new max is found :

new_max= y
result = result - oldmax + new_max

So I'll save the value of new_max :

0 + old_max - old_max + new_max = new_max`.

Obviously the code above is explicative, this is my real code :

let find_max random  = 
  let rec support rlist max =
    if rlist==[] then 0
    else 
      if (List.hd rlist) > max 
      then -max + (List.hd rlist) + support (List.tl rlist) (List.hd rlist)
      else support (List.tl rlist) max ;;
  let return = support random 0 0 ;
  !return;;

let a = [1;2;3];
print_string "max element in list is : "
print_int (find_max a);
print_string "\n"

The error is on line 9 !return;;, syntax error (obviously :/ ) on ;;

1
Hey, you have now asked three questions (the other ones are stackoverflow.com/q/62484643/20371 and stackoverflow.com/q/62497947/20371 ) where the answer is the same: not using the let ... in ... syntax properly. This was explained quite well in an answer to your first question: stackoverflow.com/a/62488711/20371 . I think you had better go and read that carefully to internalize it, and familiarize yourself with the basic syntax rules.Yawar
Hi @Yawar, yes I know I was a little stressful, sorry about that. But now I understood (more or less ) how to use "let...in". Ocaml's official doc isn't quite good I read it from here : ocaml.org/learn/tutorials/basics.html but I learn a lots of stuffs these days. Take a look to my latest question, and you'll see that I'm going better ( I hope ) : stackoverflow.com/questions/62531154/… . I need of 1-2 stuffs more and I got it.Micheal Ross

1 Answers

1
votes

There is no construct let ... = ...; in OCaml, local definition use let .. = ... in ... . You probably want to avoid using ;; altogether as a beginner too.

Also, structural equality is = and not ==. Similarly, you should never useList.hd and List.tl in your code as a beginner. Pattern matching is always the superior option. Typically, all uses of those functions can be replaced by a simple:

match rlist with
| [] -> 0
| hd :: tl -> ...

which is shorter, clearer, and eliminate any possibility to mishandle the empty list. Your logic is also unnecessarily complex rather than computing max - initial_value with

-max + hd + support tl hd

you can compute the maximum directly with

hd

You are then calling support support with too many argument. We may want to use let () = ... when computing effect, rather than using ;;.