Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Functional programming function confusion

I'm learning functional programming and am using Ocaml, but I'm having a bit of a problem with functions.

Anyway, I have a tuple and I want to return its first value. (Very simple I know, sorry)

let bach (x,y):(float*float) = (x,y);;
val bach : float * float -> float * float = <fun>

All well and good up here.

let john (x,y):(float*float) = y;;
val john : 'a * (float * float) -> float * float = <fun>

Now this is what confuses me. Why is there a 'a there? I know that it stands for a variable with an unknown type, but I'm confused as to how changing the return value adds that there.

I am a self professed n00b in functional programming, please don't eat me :)

like image 270
Secret Avatar asked Aug 02 '13 06:08

Secret


Video Answer


1 Answers

You were bitten by a subtle syntax mistake that is really non-obvious for beginners:

 let foo x : t = bar

is not the same as

 let foo (x : t) = bar

it is on the contrary equivalent to

 let foo x = (bar : t)

constraining the return type of the function.

.

So you have written

let john (x, y) = (y : float * float)

The input type is a pair whose second element, y, has type float * float. But x can be of any type, so the function is polymorphic in its type, which it represents as a type variable 'a. The type of the whole function, 'a * (float * float) -> float * float, indicates that for any type 'a, you may pass a tuple of an 'a and a (float * float), and it will return a (float * float).

This is a particular case of the snd function:

let snd (x, y) = y

which has type 'a * 'b -> 'b: for any 'a and 'b, you take a pair ('a * 'b) and return a value of type 'b.

like image 116
gasche Avatar answered Sep 21 '22 23:09

gasche