Functional Confusion Programming

I study functional programming and use Ocaml, but I have a problem with functions.

In any case, I have a tuple, and I want to return its first value. (Very easy to know, sorry)

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

Everything is good and good here.

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

Now this is what bothers me. Why is there 'a ? I know that this means a variable with an unknown type, but I'm confused about how adding the return value is added.

I myself proclaimed n00b in functional programming, please do not eat me :)

+7
functional-programming ocaml
source share
3 answers

You have been bitten by a subtle syntax error, which is really not obvious to beginners:

  let foo x : t = bar 

does not match

  let foo (x : t) = bar 

it is, on the contrary, equivalent

  let foo x = (bar : t) 

limitation of the type of the returned function.

.

So you wrote

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

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

This is a special case of the snd function:

 let snd (x, y) = y 

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

+10
source share

In both of your examples, you give type restrictions for the result of a certain function instead of your argument (as it was probably intended).

Thus,

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

means that the result of john (i.e. y ) must be of type (float * float) . Now, since at the input we have a pair consisting of x (of which nothing is known) and y (of type float * float ), the final type for input is 'a * (float * flat) .

To get what you want, you can use:

 let john ((x:float), (y:float)) = y;; 
+1
source share

If you want to learn Ocaml and functional programming in general, Coursera programming languages will be offered at Coursera again. You will learn the concepts of a programming language using SML, Racket, and Ruby, and you will receive exciting assignments to apply what you learn. Highly recommended.

-one
source share

All Articles