0
votes

how to write a function that returns the maximum number from a list of number values, if one exists. In the case it is given the empty list then it cannot return a number.

i get:

let rec max_number_list l =
    match l with 
    |[] -> None
    |x::_ -> x
    |x::xs -> max x (max_number_list xs)

I got this error "This expression has type number but an expression was expected of type int" idk how to take input number list and return output number option.

3

3 Answers

2
votes

I don't see a reason for the error you mention. In fact this code (if corrected) could be applied to any list, since max works for any OCaml type.

Aside from this, your code has type errors. Here are a couple of them to think about:

  1. Your first case returns None but your second case returns a value from the input list. If you're expecting a list of numbers this can't work. The types aren't the same.

  2. You apply max to an element of the list and the return value of a recursive call. Here again, the types don't match. The list elements are numbers, but your function returns an option type.

This looks like an assignment, so I don't want to say any more than this. It might spoil the point of it.

0
votes

Here you go:

let test l = 
  match l with
  [] -> failwith "None"
  |h::t ->  let rec helper (seen,rest) =
              match rest with 
              [] -> seen
              |h'::t' -> let seen' = if h' > seen then h' else seen in 
                         let rest' = t'
              in helper (seen',rest')
            in helper (h,t) 

Explaination:
1. Use "Failwith", which can raise exception Failure with the given string. And it won't cause type error.
2. You can define a HELPER function, which should be tail recursive.

0
votes

I would also suggest the following code :

List.fold <mylist> ~init:None ~f:(fun acc x -> if is_none acc then Some x else Some ( max (Option.value acc ~default:0) x));;