Dev Patel
Dev Patel

Reputation: 3

How can I write a function in OCaml that takes an integer list and return the element with maximum absolute value

I have tried to write code but this only returns max value and not the absolute.

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

Upvotes: 0

Views: 524

Answers (1)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66823

Imagine you had a function like max except it returns whichever of the two values has the largest absolute value. Seems like that would solve your problem.

You can start, then, by writing this function.

As a side comment, it is not legitimate to return None for some calls to a function and an integer value for other calls. They aren't the same type.

As another side comment, the second case of your match will match all nonempty lists. I think you want it to match only lists of length 1. The pattern for such a list is [x] (or you can use x :: [], which is equivalent).

Update

Here is the basic structure for defining a function that has another (helper) function inside:

let myfunc a b =
    let helper x y =
        (* Definition of helper *)
    in
    (* Definition of myfunc with calls to helper *)

Here's a concrete example, a function that returns the longest string in its input list:

let longest_string strings =
    let max_string a b =
        if String.length a >= String.length b then a else b
    in
    List.fold_left max_string "" strings

Here is an implementation of the usual max function, which might give you some ideas for writing similar functions:

let max a b =
    if a >= b then a else b

Upvotes: 1

Related Questions