Bi Bo
Bi Bo

Reputation: 1

how to write a function to find max number in a list of type number in ocaml?

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.

Upvotes: -1

Views: 16065

Answers (4)

Pierre G.
Pierre G.

Reputation: 4441

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));;

Upvotes: 0

Simplest code I can think of:

(* int list -> int *)
let max_number_list lst = List.fold_left max min_int lst

If you consider the Core library:

(* int list -> int option *)
let max_number_list lst = List.reduce lst ~f:max

Upvotes: 1

Yunhan Li
Yunhan Li

Reputation: 153

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.

Upvotes: 0

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

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.

Upvotes: 2

Related Questions