I was going through some notes and I realized something is amiss.
When emulating lazy computation (without open Lazy;) one can do the following for a stream of ones.
datatype 'a susp = Susp of (unit -> 'a)
datatype 'a stream' = Cons of 'a * ('a stream') susp
type 'a stream = ('a stream') susp
fun delay (f ) = Susp(f);
fun force (Susp(f)) = f ();
val rec ones' = fn () => Cons(1, delay(ones'));
val ones = delay(ones')
fun ltail(Susp(s)) = ltail'(force s)
and ltail' (Cons(x,s)) = s
But for getting a suspended tail the types do not match up.
operator domain: 'Z susp
operand: unit -> 'Y
What will need to change for the proper types for ltail ?
I know what happens with a tail not suspended.
I just want to figure out what the notes were saying for the suspended version.
fun ltail(Susp(s)) = ltail'(force s)
The problem here is that force takes a value of type susp, but you call it with a value of type () -> 'a. I.e. you take the function out of the susp value and then call force on the function instead of the susp value. You should just do:
fun ltail s = ltail' (force s)
Related
I want to implement the List.assoc function using List.find, this is what I have tried:
let rec assoc lista x = match lista with
| [] -> raise Not_found
| (a,b)::l -> try (List.find (fun x -> a = x) lista)
b
with Not_found -> assoc l x;;
but it gives me this error:
This expression has type ('a * 'b) list but an expression was expected of type 'a list
The type variable 'a occurs inside 'a * 'b
I don't know if this is something expected to happen or if I'm doing something wrong. I also tried this as an alternative:
let assoc lista x = match lista with
| [] -> raise Not_found
| (a,b)::l -> match List.split lista with
| (l1,l2) -> let ind = find l1 (List.find (fun s -> compare a x = 0))
in List.nth l2 ind;;
where find is a function that returns the index of the element requested:
let rec find lst x =
match lst with
| [] -> raise Not_found
| h :: t -> if x = h then 0 else 1 + find t x;;
with this code the problem is that the function should have type ('a * 'b) list -> 'a -> 'b, but instead it's (('a list -> 'a) * 'b) list -> ('a list -> 'a) -> 'b, so when I try
assoc [(1,a);(2,b);(3,c)] 2;;
I get:
This expression has type int but an expression was expected of type
'a list -> 'a (refering to the first element of the pair inside the list)
I don't understand why I don't get the expected function type.
First off, a quick suggestion on making your assoc function more idiomatic OCaml: have it take the list as the last argument.
Secondly, why are you attempting to implement this in terms of find? It's much easier without.
let rec assoc x lista =
match lista with
| [] -> raise Not_found
| (a, b) :: xs -> if a = x then b else assoc x xs
Something like this is simpler and substantially more efficient with the way lists work in OCaml.
Having the list as the last argument, even means we can write this more tersely.
let rec assoc x =
function
| [] -> raise Not_found
| (a, b) :: xs -> if a = x then b else assoc x xs
As to your question, OCaml infers the types of functions from how they're used.
find l1 (List.find (fun s -> compare a x = 0))
We know l1 is an int list. So we must be trying to find it in an int list list. So:
List.find (fun s -> compare a x = 0)
Must return an int list list. It's a mess. Try rethinking your function and you'll end up with something much easier to reason about.
I want to print a list with different element in it (for educational purpose)
I have read a tutorial that explain how to store different type in list.
type _ list =
[] : unit list
| ( :: ) : 'b * 'a list -> ('b ->'a) list;;
1 :: "e" :: 'r' :: [];; (* this is allowed *)
how I can do something like this pseudo-code:
match typeof(my_expr) with
int -> print_int
| string -> print_string
we will have "1,e,r" printed.
Some solutions i have searched
Change my type in text and printing it
Use a different type definition maybe ('a, 'b) list ?
I ask this because the OCaml toplevel know the type of every variable and show always the type in the right format: can I call this printer ?
Is there a solution only for toplevel that we can install with the #install_printer ?
I know that compiler discard type's info after the type checking pass.
The printer of the toplevel should work fine:
[1; "one"; 1.];;
- : (int -> string -> float -> unit) list =
(::) (1, (::) ("one", (::) (1., [])))
(The unoptimal printing is an unfortunate consequence of ensuring that values printed by the toplevel can be copy-pasted back to the top-level and yields the same value)
But this is only possible outside of the language itself: the toplevel printers can inspect the typing environment which is purposefully not possible in the language itself. Indeed functions like typeof would break parametricity. There is thus no universal printer function in OCaml (without looking at the internal memory representation) and no universal heterogeneous list printer.
If you want to print an heterogeneous list, there are three possible paths:
print a specific type of the heterogeneous list
let print_concrete ppf (x::y::z::rest) = Format.fprintf ppf "%f %f %f" x y z
(Contrary to appearance, this function is total: its type makes it impossible to use on lists with fewer than three elements)
Use heterogeneous lists that always pack a printing function along its main value
type 'a printer = Format.formatter -> 'a -> unit
type _ showable_list =
| [] : unit showable_list
| (::):
('a * 'a printer) * 'b showable_list
-> ('a -> 'b) showable_list
let rec print: type a. a showable_list printer =
fun ppf l -> match l with
| [] -> ()
| (a,printer) :: rest -> Format.fprintf ppf "%a# %a" printer a print rest
provide a matching heterogeneous list of printing functions
type 'a plist =
| []: unit plist
| (::): 'a printer * 'b plist -> ('a -> 'b) plist
let rec print: type l. l plist -> l list printer = fun printers ppf values ->
match printers, values with
| [], [] -> ()
| p :: prest, a :: rest -> Format.fprintf ppf "%a# %a" p a (print prest) rest
The fact that you often need to specialize the heterogeneous list type may make it worthwhile to introduce a functor for generating them:
module Hlist(Specialization: sig type 'a t end) = struct
open Specialization
type 'a list =
| []: unit list
| (::): 'a t * 'b list -> ('a -> 'b) list
end
then the previous specialized type can be constructed with
module Showable_list = Hlist(struct type 'a t = 'a * 'a printer end)
module Printer_list = Hlist (struct type 'a t = 'a printer end)
I am trying to write a quicksort function of type
'a list * ('a * 'a -> bool) -> 'a list
but for some reason I am getting:
'a list -> ('a * 'a -> bool) -> 'a list
Here is my code for the function:
fun quicksort xs f = let
fun qs [] = []
| qs [x] = [x]
| qs (p::xs) = let
val (less, more) = List.partition (fn x => f (x, p)) xs
in
qs less # p :: qs more
end
in
qs xs
end
When I call the function I get this error:
stdIn:73.1-73.18 Error: operator and operand don't agree [tycon mismatch]
operator domain: 'Z list
operand: int list * (int * int -> bool)
in expression:
quicksort (L, op <)
I realize that I must be passing it in wrong, but I just can't see my mistake. So, my question is what is going on here in which I get this error while trying to pass in my list and operator?
You could simple change:
fun quicksort xs f = let
to:
fun quicksort (xs,f) = let
since you want quicksort to have as parameters a tuple (xs,f).
I've got a basic function which checks a list for duplicates and returns true if they are found, false otherwise.
# let rec check_dup l = match l with
[] -> false
| (h::t) ->
let x = (List.filter h t) in
if (x == []) then
check_dup t
else
true
;;
Yet when I try to use this code I get the error
Characters 92-93:
let x = (List.filter h t) in
^
Error: This expression has type ('a -> bool) list
but an expression was expected of type 'a list
I don't really understand why this is happening, where is the a->bool list type coming from?
The type ('a -> bool) list is coming from the type of filter and from the pattern match h::t in combination. You're asking to use a single element of the list, h, as a predicate to be applied to every element of the list t. The ML type system cannot express this situation. filter expects two arguments, one of some type 'a -> bool where 'a is unknown, and a second argument of type 'a list, where 'a is the same unknown type as in the first argument. So h must have type 'a -> bool and t must have type 'a list.
But you have also written h::t, which means that there is another unknown type 'b such that h has type 'b and t has type 'b list. Put this together and you get this set of equations:
'a -> bool == 'b
'a list == 'b list
The type checker looks at this and decides maybe 'a == 'b, yielding the simpler problem
'a -> bool == 'a
and it can't find any solution, so it bleats.
Neither the simpler form nor the original equation has a solution.
You are probably looking for List.filter (fun x -> x = h) t, and you would probably be even better off using List.exists.
For complete this answer I post the final function for search duplicate value in array:
let lstOne = [1;5;4;3;10;9;5;5;4];;
let lstTwo = [1;5;4;3;10];;
let rec check_dup l = match l with
[] -> false
| (h::t) ->
let x = (List.filter (fun x -> x = h) t) in
if (x == []) then
check_dup t
else
true;;
and when the function run:
# check_dup lstOne
- : bool = true
# check_dup lstTwo
- : bool = false
#
I am trying to implement a concurrent list using CML extensions of Standard ML but i am running into errors that are probably to do with my being a newbie in Standard ML. I have implemented the clist as having an input and output channel and I store the list state in a loop. However my code does not compile and gives errors below
structure Clist : CLIST =
struct
open CML
datatype 'a request = CONS of 'a | HEAD
datatype 'a clist = CLIST of { reqCh : 'a request chan, replyCh : 'a chan }
(* create a clist with initial contents l *)
val cnil =
let
val req = channel()
val reply = channel()
fun loop l = case recv req of
CONS x =>
(loop (x::l))
|
HEAD => (send(reply, l); loop l)
in
spawn(fn () => loop nil);
CLIST {reqCh=req,replyCh=reply}
end
fun cons x (CLIST {reqCh, replyCh})=
(send (reqCh, CONS x); CLIST {reqCh = reqCh, replyCh = replyCh})
fun hd (CLIST {reqCh, replyCh}) = (send (reqCh, HEAD); recv replyCh)
end
This is the signature file
signature CLIST =
sig
type 'a clist
val cnil : 'a clist
val cons : 'a -> 'a clist -> 'a clist
val hd : 'a clist -> 'a
end
Errors I am getting:
clist.sml:21.4-21.35 Error: operator and operand don't agree [circularity]
operator domain: {replyCh:'Z list chan, reqCh:'Z list request chan}
operand: {replyCh:'Z list chan, reqCh:'Z request chan}
in expression:
CLIST {reqCh=req,replyCh=reply}
So your problem is in your definition of clist
datatype 'a clist = CLIST of { reqCh : 'a request chan, replyCh : 'a chan }
This is saying that the request channel takes in a request of 'a and replies with a 'a. This is not consistent with your implementation. When you send a CONS x request on the channel, you are saying add x of type 'a to the list, but when you send a HEAD request, you are saying give me back the entire list. Thus, a CONS request should take a 'a and a HEAD request should return a 'a list. You can fix your problem by changing your clist definition to
datatype 'a clist = CLIST of { reqCh : 'a request chan, replyCh : 'a list chan }
I would also suggest changing your definition of cnil to a unit -> 'a clist function, this way you can create distinct concurrent lists.
For example:
val l1 = Clist.cnil()
val l2 = Clist.cnil() (*cons'ing onto l2 won't affect l1*)