1

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);;
prmz
  • 311
  • 1
  • 3
  • 13

2 Answers2

2

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 ...
Community
  • 1
  • 1
gasche
  • 31,259
  • 3
  • 78
  • 100
  • I tried with if .. then .. else but always get Syntax error. I will try to figure out something and get back the answer when i have it. Thank you for that learning material. – prmz Jun 18 '13 at 08:39
1

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)
prmz
  • 311
  • 1
  • 3
  • 13