feded
feded

Reputation: 139

Use of " _ " in functions Ocaml

If I have a function that hasn't arguments and works on a list, like :

let listToCheck = function
 [] -> raise (Failure "No elements")
 | hd :: tl -> returnTrueOrFalse _ (*Where "_" should be the list*)

With returnTrueOrFalse defined as :

let returnTrueOrFalse list_ = .... (*returns true or false*)
.
(*some code*)
.
let isTrue = listToCheck [1;2;3] in isTrue

Now, listToCheck is called on a list and hasn't paramenters.

On the other hand returnTrueOrFalse needs of an argument.

Since listToCheck is a function to call on a list, can I pass that list as argument for returnTrueOrFalse using _ inside listToCheck ? If yes, how?

Upvotes: 0

Views: 74

Answers (2)

Jeffrey Scofield
Jeffrey Scofield

Reputation: 66808

Your function doesn't really need to do a pattern match at all:

let listToCheck list =
    if list = [] then failwith "No elements"
    else returnTrueOrFalse list

However you're probably asking a more general question, not about this particular code. For the general case I think the as pattern is probably what you're looking for, as @Bergi suggests.

Upvotes: 1

Bergi
Bergi

Reputation: 664185

You can reconstruct the list, or alias the pattern, or just don't split into head and tail at all:

let listToCheck = function
  | []       -> raise (Failure "No elements")
  | hd :: tl -> returnTrueOrFalse (hd::tl)
let listToCheck = function
  | []                 -> raise (Failure "No elements")
  | (hd :: tl) as list -> returnTrueOrFalse list
let listToCheck = function
  | []   -> raise (Failure "No elements")
  | list -> returnTrueOrFalse list

Upvotes: 1

Related Questions