Map function on a list in Standard ML - sml

Based on this definition:
An append list is a (simple) implementation of the list abstract data type that makes construction cheap (O(1)), but makes destruction expensive (O(n)). The 'a alistNN and 'a alist types are defined as follows:
datatype 'a alistNN = Sing of 'a | Append of 'a alistNN * 'a alistNN
datatype 'a alist = Nil | NonNil of 'a alistNN
The 'a alistNN type represents the “non-nil” append lists, while the 'a alist type represents arbitrary (nil or non-nil) append lists.
Im asked to make a map function defined as:
fun alistMap (f: 'a -> 'b) (xs: 'a alist): 'b alist =
That performs a map on an append list.
I have it defined as follows:
fun alistMap (f: 'a -> 'b) (xs: 'a alist): 'b alist =
case xs of
Nil => Nil
| NonNil xs =>
let
fun mapNN(f: 'a -> 'b) (xs: 'a alist): 'b alist =
case xs of
Sing x => Sing (f x)
| Append (ys, zs) =>
let
val ws = mapNN f ys
val ts = mapNN f zs
in
alistAppend (ys , zs)
end
in
mapNN f xs
end
I keep getting clashing types, especially with:
Sing x => Sing (f x)
Any idea what might be causing this?

Your inner function mapNN is annotated with the wrong type. The constructors Sing and Append form values of type alistNN, not alist. So it should instead be annotated as follows.
fun mapNN (f : 'a -> 'b) (xs : 'a alistNN) : 'b alistNN = ...
There are a couple other issues with your code:
The line alistAppend (ys, zs) has type 'a alist but the function needs to return something of type 'b alistNN, so this will be a type error. As a hint to fix this problem, notice that you create values ws and ts but then never use them... ;)
Once you fix mapNN, you will have a type error on the line mapNN f xs, because it has type 'b alistNN, but needs to be something of type 'b alist.
In summary, be careful about the difference between alist and alistNN. These are two different types, with different constructors, and fundamentally different meanings!

Related

Signature declaration changed on compilation

When I try to compile my code, I get the following error
Error: Signature mismatch:
...
Values do not match:
val filter_map : ('b -> 'b option) -> 'b t -> 'b list
is not included in
val filter_map : ('b -> 'a option) -> 'b t -> 'a list
File "set.ml", line 7, characters 2-55: Expected declaration
File "treeSet.ml", line 105, characters 10-20: Actual declaration
However, my signature is actually declared as follows.
module type SetS = sig
type 'a t
val empty : 'a t
val insert : 'a t -> 'a -> 'a t
val contains : 'a t -> 'a -> bool
val filter_map : ('a -> 'b option) -> 'a t -> 'b list
end
For some reason, the error I get when compiling shows a different type declaration than the one I have actually implemented. Why is this happening and how can I fix this?
The error Signature mismatch means that the derived signature of a module differs from the specified signatures. E.g., suppose we want to write a module with the following signature,
module type Expected = sig
val filter : ('a -> bool) -> 'a list -> 'a list
end
and we write,
module Real : Expected = struct
let filter = List.filter_map
end
The error message that we get will be,
Signature mismatch:
Modules do not match:
sig val filter : 'a list -> f:('a -> 'b option) -> 'b list end
is not included in
Expected
Values do not match:
val filter : 'a list -> f:('a -> 'b option) -> 'b list
is not included in
val filter : ('a -> bool) -> 'a list -> 'a list
So the problem is that our proposed implementation of filter has type 'a list -> f:('a -> 'b option) -> 'b list but what we really wanted and expected for the type of filter is ('a -> bool) -> 'a list -> 'a list. That is what the error message says.
Applying to your case, your implementation has the inferred type ('b -> 'b option) -> 'b t -> 'b list which doesn't match with the required type ('b -> 'a option) -> 'b t -> 'a list. Notice that your type is less general. It filters list without changing the type of the element. So it can only filter map int list to int list, string list to string list and so on, unlike the more generic implementation that is able to map int list to string list.
To rectify the problem, you need to carefully review your implementation. Make sure that you don't have branching instructions (like if/then/else, match) such that one branch returns an element or elements of the input list and the other branch returns the element or elements of the output list. To demonstrate this, consider the following implementation,
let rec filter_map f = function
| [] -> []
| x :: xs -> match f x with
| None -> xs
| Some x -> x :: filter_map f xs
Here I made an error, by returning xs, the input list, when f x evaluates to None. The other branch, constructs the output list, so we got the types of input and output lists unified. In the correct implementation, you should recursively call filter_map in both branches,
let rec filter_map f = function
| [] -> []
| x :: xs -> match f x with
| None -> filter_map f xs
| Some x -> x :: filter_map f xs

What does this type error on heterogeneous lists means?

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.

OCaml unexpected type

I have to write a function to remove elements from a lazy list. Indexes of elements to be removed are in list xs.
I don't know where I should sort xs? When I try in this way I get "Error: This expression has type...".
type 'a llist = LNil | LCons of 'a * (unit -> 'a llist)
let rec remove xs ll =
let rec helper =
function
| (_, i, LNil) -> LNil
| (h::t, i, LCons(x, xf)) -> if h = i then helper (t, (i + 1), xf())
else LCons(x, fun() -> helper (h::t, (i + 1), xf()))
| ([], i, LCons(x, xf)) -> LCons(x, xf)
in helper (List.sort xs, 0, ll);;
List.sort from OCaml standard library has the following interface:
val sort : ('a -> 'a -> int) -> 'a list -> 'a list
That means, that it accepts a function and a list. The function should have type 'a -> 'a -> int, i.e., it takes two elements of arbitrary type 'a and returns a value of type int that defines the mutual order of the arguments. The second argument is a list of values, where each value has type 'a. A usual invocation of the sort function is:
List.sort compare [2;1;4;3]
So with this knowledge we can tackle with your program:
You invoke List.sort on xs this has two consequences:
type inference system concludes that xs is a function of type 'a -> 'a -> int.
The result of List.sort xs is a function of type 'a list -> 'a list. This is because, List.sort requires two arguments, but you provided only one.
(List.sort xs) is a function that takes a list & returns a list - as xs is supposed to be the function that sorts the element of the list; you miss to pass a list as arg.
...whereas a list is expected.

Ocaml Type-inference of fun f [x; y; z] -> (f x y), (f z);;

I have this OCaml function:
fun f [x; y; z] -> (f x y), (f z);;
and the teacher wants me to answer: what is the type of this function.
But i do not understand what does [x; y; z] means? Is it a list ? i don't think so because the solution is
('a -> 'a-> 'b) -> 'a list -> b*('a->'b))
and it means that z is of different type and I cannot undestand how do I get it. Is it a vector? a sequence of three inputs? don't think so neither because otherwise it would be
fun f x y z -> (f x y), (f z);;
Can someone help me?
Okay, let's evaluate type of fun f [x; y; z] -> (f x y), (f z) this.
Our function takes to arguments and returns a tuple. So it's type will be _ -> _ -> _ * _ where underscores are not evaluated yet parts. We will evaluate them below
Our 2nd argument is a list , so types of x , y and z are the same.
_ -> 'a list -> _ * _
when we look at 1st expression in result tuple (f x y) we see that f is applied to x and y, so we can rewrite result as:
('a -> 'a -> 'b) -> 'a list -> 'b * _
in second expression in function result expression we see f z. But we already know that f is 'a -> 'a -> 'b already, so it seems that f z has type 'a -> 'b.
('a -> 'a -> 'b) -> 'a list -> 'b * ('a -> 'b)
Et voilà!
This is a list for sure. It cannot be anything else.
Your function accepts two arguments. The first one is a function, and the second is a list, that is deconstructed into three values. The function accepts two arguments. Since all functions in OCaml is currified it can also accept one argument and "return" a function that will accept the other argument and yield a result.
So, at the end you have a pair of a result of an application of function f to the first two elements of a list, and a partial application of the same function to the third element of a list.
Hope, this answers your questions.

Function of type ('a -> 'b) list -> 'a -> 'b list in OCaml

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