prmz
prmz

Reputation: 311

Ocaml - using one function in another

I'm learning Ocaml and having hard time understanding how to use first function as argument of another.

For example, I created a function bigger

# let bigger (a,b) = match (a,b) with
  (a,b) -> if a > b then true else false;;
  val bigger : 'a * 'a -> bool = <fun>

# bigger (2,3);;
- : bool = false
# bigger (3,2);;
- : bool = true

Now I'm struggling to use this function as an argument in function sortPair - it sorts both elements: - if bigger = true then (a,b) - if bigger = false then (b,a)

I'm sure it's a very simple solution, but I really want to understand this basic problem before moving on further.

This is what I tried:

# let sortPair (a,b) = match (a,b) with
  bigger (a,b) -> if true then (a,b) else (b,a);;

Upvotes: 1

Views: 165

Answers (2)

prmz
prmz

Reputation: 311

Ok so i did exactly as @gasche said, it's a very simple solution after all, I complicated the problem for no reason:

# let sortPair (a,b) = if bigger (a,b) then (a,b) else (b,a);;
val sortPair : 'a * 'a -> 'a * 'a = <fun>

# sortPair (2,3);;
- : int * int = (3, 2)

I did get a little different syntax that i was hoping for though.

('a*'a -> ('a*'a -> bool) -> 'a*'a)

Upvotes: 1

gasche
gasche

Reputation: 31459

You don't have the basic syntax of match right. You should look carefully at your learning material (see here for pointers to beginners material).

Given that bigger (a, b) returns a boolean, you can use the if .. then .. else form:

if bigger(a,b) then ... else ...

Upvotes: 2

Related Questions