I want to write a function of type
int -> 'a -> (int, int) slowa list
I was wondering would I necessarily need to defing first a type slowa
If so, this is how I defined my "slowa"
type slowa =
(_,_)
|('a, 'b) of int * int
;;
Where slowa is of type (int, int)
But I'm not sure how if I am thinking right. I'd appreciate some help. I'm new to this :)
EDIT:
So now I went ahead to try this:
type ('b, 'a) slowa = int * 'b
let c = 3, 5;;
let d = 1, 3;;
let rec add k v d =
match d with
| [] -> [(k, v)]
| (k', v')::t ->
if k = k'
then (k, v) :: t
else (k', v') :: add k v t
;;
but I want it the type of the function add to be like this type: int -> 'a -> (int, int) slowa list
It would be easier if I wanted to return just list but now the return type is int -> 'a -> (int, int) slowa list which gets confusing... :/ I stand to be correct on the number/type of parameters.
If you just want a type that's a synonym for int * int (pairs of ints), you can define it like this:
type slowa = int * int
In this case, the name is just a synonym. You could always replace uses of the name by the definition. So you don't actually need to make the definition (it's good for documentation).
If you want to define a new type, you need to define a constructor for it:
type myslowa = Slow of int * int
This defines a new type. Values of the type look like Slow (3, 4). These values have a type different from all others; i.e., they are not interchangeable with pairs of ints.
If you want to define a parameterized type, you need to include the parameter(s) in your definition:
type ('a, 'b) pslowa = 'a * 'b
Since there's no new constructor, this is also just a synonym. But it's a synonym for an infinite set of types. In particular, it's a synonym for pairs of any two types.
If you want to define a new, parameterized type, you need to have both parameters and a constructor:
type ('a, 'b) mypslowa = Slow of 'a * 'b
This combines the properties; i.e., it is a new type that represents pairs of any two types.
I hope this helps; one of these might be close to what you're looking for.
Update
With your new definition of slowa, the type (int, int) slowa is identical to the type int * int. When the toplevel shows you the type of something, it has to choose among all the ways of representing the type. I think what you're saying is that the toplevel chooses to use int * int rather than (int, int) slowa. It's best not to get too hung up on this (IMHO). The one thing you might try is to annotate your types:
type ('b, 'a) slowa = int * 'b
let c = 3, 5;;
let d = 1, 3;;
let rec add k v (d: ('a, 'b) slowa list) : ('a, 'b) slowa list =
match d with
| [] -> [(k, v)]
| (k', v')::t ->
if k = k'
then (k, v) :: t
else (k', v') :: add k v t
;;
(Your definition of slowa looks a little strange, since you're not using the 'a parameter for anything.)
Related
If I have a function f defined as
f: 'a -> 'b -> c' -> d'
Does that mean it takes one argument? Or 3? And then it outputs one argument? How would I use or call such a function?
As Glennsl notes in the comments, it means both.
Very briefly, and by no means comprehensively, from an academic perspective, no function in OCaml takes more than one argument or returns more or less than one value. For instance, a function that takes a single argument and adds 1 to it.
fun x -> x + 1
We can give that function a name in one of two ways:
let inc = fun x -> x + 1
Or:
let inc x = x + 1
Either way, inc has the type int -> int which indicates that it takes an int and returns an int value.
Now, if we want to add two ints, well, functions only take one argument... But functions are first class things, which means a function can create and return another function.
let add =
fun x ->
fun y -> x + y
Now add is a function that takes an argument x and returns a function that takes an argument y and returns the sum of x and y.
We could use a similar method to define a function that adds three ints.
let add3 =
fun a ->
fun b ->
fun c -> a + b + c
The type of add would be int -> int -> int and add3 would have type int -> int -> int -> int.
Of course, OCaml is not purely an academic language, so there is convenience syntax for this.
let add3 a b c = a + b + c
Inferred types
In your question, you ask about a type 'a -> 'b -> 'c -> 'd``. The examples provided work with the concrete type int. OCaml uses type inferencing. The compiler/interpreter looks at the entire program to figure out at compile time what the types should be, without the programmer having to explicitly state them. In the examples I provided, the +operator only works on values of typeint, so the compiler _knows_ incwill have typeint -> int`.
However, if we defined an identity function:
let id x = x
There is nothing her to say what type x should have. In fact, it can be anything. But what can be determined, if that the function will have the same type for argument and return value. Since we can't put a concrete type on that, OCaml uses a placeholder type 'a.
If we created a function to build a tuple from two values:
let make_tuple x y = (x, y)
We get type 'a -> 'b -> 'a * 'b.
In conclusion
So when you ask about:
f: 'a -> 'b -> 'c -> 'd
This is a function f that takes three arguments of types 'a, 'b, and 'c and returns a value of type 'd.
I have a heterogeneous list and a function on them
type ('ls,'tl) hlist =
| Nil : ('a,'a) hlist
| Cons: 'a * ('l, 't) hlist -> ('a -> 'l, 't) hlist
let rec headlist l =
match l with
| Cons (h, t) -> Cons (head h, headlist t)
| Nil -> Nil
and would like to traverse a hlist of lists of different types, and build a list of the heads of each list. The idea is something like this:
headlist Cons( [1,2,3], Cons( ['a','b'], Cons( [true,false], Nil )))
= Cons( 1, Cons( 'a', Cons( true, Nil)))
However, I encounter a type error.
Error: This expression has type ('a, 'b list -> 'a) hlist
but an expression was expected of type
('b list -> 'a, 'b list -> 'a) hlist
The type variable 'a occurs inside 'b list -> 'a
I don't understand the type error. What is it saying? Am I trying to do something impossible?
Your problem start with the fact that it is not possible to write a type for the headlist function that you have in mind. Since it is in general necessary to write explicitly the type of functions manipulating GATDs, it is good practice to start writing this type, to check that one can write the type; and only remove it afterward in the rare cases where it is possible to elide the explicit type annotations.
The root of the issue here is that heterogeneous lists are much more rigid than normal lists. In particular, depending on the operations needed on such lists, it is frequent to have to tailor specialized heterogeneous list types. For instance, with the classical heterogeneous list:
type void = |
module Hlist = struct
type 'a t =
| []: void t
| (::): 'a * 'l t -> ('a -> 'l) t
let head(x::_) = x
let rec length: type a. a t -> int = function
| [] -> 0
| a :: q -> 1 + length q
end
it is impossible to express the condition: all elements of the heterogeneous list are heterogeneous lists with at least one element themselves. However, it is possible to define another list type that does enforce this condition:
module Hlist_of_nonempty_hlist_0 = struct
type 'a t =
| []: void t
| (::): (('h -> 'more) as 'a) Hlist.t * 'l t -> ('a -> 'l) t
end
With this new list type, I can compute the length of all nested lists:
let rec map_length: type a. a Hlist_of_nonempty_hlist_0 t -> int list = function
| [] -> []
| a :: q -> Hlist.length a :: map_length q
However, I can still not apply head to all elements, because the types of the head are not easily accessible. One option is to store those types directly in the type of Hlist_of_nonempty_hlist:
module Hlist_of_nonempty_hlist = struct
type ('a,'b) t =
| []: (void,void) t
| (::):
(('h -> 'more) as 'a) Hlist.t * ('l,'hl) t
-> ('a -> 'l, 'h -> 'hl) t
end
and with this specialized heterogeneous list type, writing the type of map_head becomes straightforward:
let rec map_head:
type l hl. (l, hl) Hlist_of_nonempty_hlist.t -> hl Hlist.t
= function
| [] -> []
| (a::_) :: q -> a :: map_head q
But this is a lot of design work on the type for one function. And going further and trying to write any generic functions over heterogeneous lists generally require a lot of polymorphic records and functors.
I don't think there's a type that describes the function you want. You want to say that the input is an hlist all of whose heterogeneous types are lists. I don't see a way to say that, which suggests to me that you can't have a function like this.
However, I have been wrong many times, and GADTs are something I'm particularly unsteady about.
If I understand correctly, your function headlist is supposed to have type ('a list -> 'b list -> ... -> 'z, 'z) hlist -> ('a -> 'b -> ... > 'z, 'z) hlist. I do not think there is a single OCaml type that covers all the possible arities. So, the compiler looks for a much simpler type, hence the strange error message.
(* val bar = fn : (’a * ’b -> ’b) -> ’b -> ’a list -> ’b *)
fun bar f b nil = b
| bar f b (h::t) = f (h, bar f b t)
This function was given to us with the instructions of explaining what it does. The only further information given are that the parameters are a binary function, a value, and a list. From looking at it, I already know that if the list is nil, it returns the b value, otherwise it applies the binary function to the list head and recurses. I just don't understand how to interpret this line:
(* val bar = fn : (’a * ’b -> ’b) -> ’b -> ’a list -> ’b *)
There are numerous tutorials explaining SML's typing, but I can't find anything in-depth enough to apply to this. Could anyone translate it to English so I know how it works for future reference?
To understand this type sgnature, you need to first understand currying.
A definition like
fun sum a b = a + b
has type int -> int -> int.
It is a function of one variable (an integer) where the return value is itself a function, one which sends ints to ints.
For example, val f = sum 1 assigns to f the function which adds one to its input (in other words, the successor function) so that, e.g., f 5 evaluates to 6.
In practice, such functions are often used like sum 3 4 but what is happening there isn't the passing of 2 values to sum. Rather, the one value 3 is passed, which returns a function, and this returned value is then applied to 4. Thus, sum 3 4 should be parsed as (sum 3) 4 rather than sum (3,4) -- which would be a type error.
Note that this is fundamentally different from something like
fun add (a,b) = a + b
which is a function of two variables, it has type int * int -> int, which is different than sum's type of int -> int -> int. The latter is not syntactic sugar for the former, but instead has a fundamentally different semantics.
When reading something such as int -> int -> int, you should read it as right-associative. In other words, it is the same as int -> (int -> int).
Another thing that is happening with ('a * 'b -> 'b) -> 'b -> 'a list -> 'b is the use of type variables 'a, 'b. This means that the type you are trying to parse is of a higher-order polymorphic function. It 'a and 'b can represent any type.
Putting it all together, a function, f, of type ('a * 'b -> 'b) -> 'b -> 'a list -> 'b is a function which takes as input any function whose type is of the form 'a * 'b -> 'b (a function of two variables whose return type is the type of the second variable). The return value of f is a function of the form 'b -> 'a list -> 'b. This latter is a function which takes an element of type 'b and returns a function which sends 'a lists to objects of type 'b
You could summarize it by saying that f is a curried function which takes a function of type ('a * 'b -> 'b), a value of type 'b, a list of values of type 'a, and returns a value of type 'b. That is accurate enough, but don't slip into thinking of it as equivalent to a function of type
('a * 'b -> 'b) * 'b * 'a list -> 'b
By the way, two of the most useful functions in SML, foldl and foldr have type ('a * 'b -> 'b) -> 'b -> 'a list -> 'b, so this isn't merely an academic exercise. Being able to unpack such type descriptions is a key to being able to use such functions correctly.
I was able to find the solution based on what is apparently called type inferencing. I had never learned this before but
(* val bar = fn : (’a * ’b -> ’b) -> ’b -> ’a list -> ’b *)
is display of argument and return types for the function.
(’a * ’b -> ’b) refers to the first argument function. It requires 2 arguments ('b and 'a) in itself and returns 1 value 'b.
'b refers to the second argument, a value.
'a list refers to a list of values, the third argument in the function.
Finally, the last 'b is the return value.
I tried to find this somewhere in internet, but I failed to do this. I want to learn OCaml and that's difficult to understand for me, how to do this.
My question is - how can I easy write a function, when I have a signature. For example - I have a signature like this:
((int -> int) -> int -> int -> int) -> (int -> int) -> int -> int -> int
and I want to write a function, that have signature like this above. Would someone help me or try to explain this? I would be very grateful :)
A function with type 'a -> 'b, takes values of some type 'a and returns values of some type 'b. To use specific types, a function of type int -> int takes an int and returns an int. This is the type of integer negation, for example.
One way to look at a function with type 'a -> 'b -> 'c is that it takes two values, of type 'a and 'b, and returns a value of type 'c. A specific example would be the type int -> int -> int, which is the type of integer addition (say):
# (+);;
- : int -> int -> int = <fun>
This pattern continues for more arguments.
The type you give has this type at the high level: 'a -> 'b -> 'c -> 'd -> 'e. So, it's a function with four arguments.
The first argument has type (int -> int) -> int -> int -> int, which is itself quite complicated. The second argument has type int -> int, described above. The third and fourth arguments have type int. The function returns an int.
Using this same analysis on the first argument, you can see that it's a function with three arguments. The first is a function of type int -> int, and the second and third are of type int. This function returns an int.
Here's a function of type (int -> int) -> int -> int -> int:
let myfun f a b =
(f a) + a + b
You can see the type in the OCaml toplevel:
# let myfun f a b =
(f a) + a + b;;
val myfun : (int -> int) -> int -> int -> int = <fun>
#
You should be able to work out the rest. I don't want to take all the enjoyment out of the problem by giving a full answer.
Write any Ocaml function whose type is ('a -> 'b) list -> 'a -> 'b list
('a -> 'b) list is the part that confuses me the most. I'm new to OCaml and having a hard time understanding how to write a function to get a specific datatype type.
# let int x = x+1;;
# let fcn = [int; int];;
So I'm passing a function a function and a variable. I'm going to take that variable an add it to each element of the list and return the list?
('a -> 'b) means a function which goes from type 'a to type 'b. Basically you need to make a function which takes a list of functions that take 'a and return 'b, plus a specific 'a value, and which returns a list of 'b values (probably by applying each function of the list of functions to the specific 'a value).
As this is homework, I will not provide you with a complete solution. But, as a hint, I would suggest that you take a look at this implementation of the familiar map function:
let rec map f = function
| [] -> []
| x :: xs -> f x :: map f xs
It has type ('a -> 'b) -> 'a list -> 'b list which means that it takes as its first argument a function that takes values of some type 'a to values of some type 'b, as its second argument a list of elements of type 'a, and that it produces a list of elements of type 'b. It proceeds by pattern matching on the argument list and, recursively applying the function (f) to every element x of the list.
Now have a look at the type of the function that you have to write? What does it tell you about the required behaviour of that function? Keeping the implementation of the map function in mind, how would you write your function?
('a -> 'b) list -> 'a -> 'b list
This means that your function has two parameters
A list of ('a -> 'b) which represents a function taking an element of type 'a as a parameter and returning an element of type 'b. As you can see, these types are abstract, so they could be of any types for instance (int -> int) or (int -> float) etc...
An elements of types 'a. Notice that this type must be the same as the parameter of your function.
So you'll build the resulting list with the element you give as a parameter.
Here is a little example:
let action l a =
let rec todo l res =
match l with
| [] -> res
| h :: t -> todo t res#[h a] in
todo l []
so here, any function of type int -> int will be accepted. The same thing goes for any other type as long as you don't mix them with other types.
let rec func f a = match f with (* ( 'a->'b ) list -> 'a -> 'b list *)
|[]->[]
|x::lr -> x a :: func lr a;;
that may help ! it works fine
1 - So as we know , ocaml create the type of our function line by line
2 - in this function we have two arguments f and a
3 - ( 'a->'b ) list : for f
4 - 'a : for a ! how ocaml did that ? listen !
5 - when we matched f with [ ] 'blank list' ocaml release that is a list (****)list but doesn't know what contains yet in the last line of the code he will do ok ? nice !
- here we are in the last line of the code and we have only f of type list -
6 - x :: lr means we sort the first element of the element that is matched before : f and we add a here ocaml gives a type for a and for the list elements which is matched : f as first elements ocaml gives them types from 'a to 'z so here we have ('a->'b) list for f and 'a for a
-here we have f of type : ('a->'b) list , and a of type : 'a
7 - the result of this function 'b list so it's up to you to answer in comment ! :D thank you