How to use a set comprehension for the body of a function - alloy

Suppose I have the following signatures:
sig A {}
sig B {}
sig P {
a: A,
b: B
}
How can I write a function f, say, such that f returns the set of P for which each member has the value x: A for its a field?
Entering the expression {p: P | p.a = x} into the evaluator gives me back a set, but when I try to define f in this manner
fun f(a: A) : set P {
{ p: P | p.a = a }
}
alloy tells me I've made an error:
A type error has occurred
This cannot be a legal relational join where
left hand side is p (type = {this/P})
right hand side is a (type = {this/A})

The problem is that you shadowed the a relation with your function parameter. It works if you replace f(a: A) with f(a': A). Alternatively, you can use the # operator, which returns the global instead of local value of a set:
fun f(a: A) : set P {
{ p: P | p.#a = a }
}

Related

Structures and Pattern Matching

I have a struct Context that as a type takes an association list from string to a custom type process.
I'm trying to pattern match to see if my struct is empty (this seems to work fine) however checking whether my struct contains elements is giving me the following error.
File "src/main.ml", line 131, characters 13-30:
131 | | Context.((ext_ref,prc)::tl) ->
^^^^^^^^^^^^^^^^^
Error: This pattern matches values of type 'a list
but a pattern was expected which matches values of type t
Here is the code that won't compile:
(* Finds a recv corresponding to a send stmt *)
let rec find_recv (ctx: Context.t) (external_ref:variable) =
match ctx with
| Context.(empty) -> None
| Context.((ext_ref,prc)::tl) ->
begin
match prc with
| Prc(_, _,Recv(_,_,chn,_)) -> if chn = external_ref then Some prc else find_recv tl external_ref
|_ -> find_recv tl external_ref
end
Here is the signature for the 'Context' struct.
module type Context = sig
type t
val empty : t
val lookup : t -> string -> process
val extend : t->string ->process -> t
val filter : t->string ->t
end
Here is the instantiation of my Context module:
(** Instantiating a Process Table *)
module Context : Context = struct
type t = (string * process) list
let empty = []
let lookup (ctx:t) (x:string): process=
let chck = List.assoc_opt x ctx in match chck with
|Some i -> i
|None -> Null("")
let extend (ctx:t) (x:string) (ty:process) =
(x, ty) :: ctx
let filter ctx x =
List.remove_assoc x ctx
end
I got this code from the Real World Ocaml book.
Given the constraints of your Context signature, type t within the Context module is abstract.
Within the module, your functions know that empty is a list. However, outside of it, empty is merely of abstract type Context.t.
Let's look at a simpler example:
utop # module type S =
sig
type t
val empty : t
end
module M : S =
struct
type t = int list
let empty = []
end;;
module type S = sig type t val empty : t end
module M : S
utop # M.empty;;
- : M.t = <abstr>
utop # match M.empty with [] -> "hello" | _ -> "world";;
Error: This pattern matches values of type 'a list
but a pattern was expected which matches values of type M.t
M.t is abstract. We know it exists, but not how it is implemented. This abstraction is frequently useful in designing applications.
It is possible to break this abstraction. Whether it's a good idea is a matter of opinion and outside of Stack Overflow's scope.
utop # module M2 : S with type t = int list =
struct
type t = int list
let empty = []
end;;
module M2 : sig type t = int list val empty : t end
utop # match M2.empty with [] -> "hello" | _ -> "world";;
- : string = "hello"
As kindly pointed out by #glennsl and as is explained better than I can in this thread Unbound constructor error when using module signature
My problem can be solved by including the find_recv function within the Modules signature as below.
module type Context = sig
type t
val empty : t
val lookup : t -> string -> process
val extend : t->string ->process -> t
val filter : t->string ->t
val find_recv: t -> variable -> process option
end
Obviously this must then be instantiated before use.

Is there a way to obtain a 'reference' to a mutable struct field

So I have a record type with mutable field:
type mpoint = { mutable x:int ; mutable y: int };;
let apoint = { x=3 ; y=4};;
And I have a function that expects a 'ref' and does something to its contents.
For example:
let increment x = x := !x+1;;
val increment : int ref -> unit = <fun>
Is there a way to get a 'reference' from a mutable field so that I can pass it to the function. I.e. I want to do something like:
increment apoint.x;; (* increment value of the x field 'in place' *)
Error: This expression has type int but an expression was expected of type
int ref
But the above doesn't work because apoint.x returns the value of the field not its 'ref'. If this was golang or C++ maybe we could use the & operator to indicate we want the address instead of the value of the field: &apoint.x.
(How) can we do this in Ocaml?
PS: Yes, I know its probably more common to avoid using side-effects in this way. But I promise, I am doing this for a good reason in a context where it makes more sense than this simplified/contrived example might suggest.
There's no way to do exactly what you ask for. The type of a reference is very specific:
# let x = ref 3
val x : int ref = {contents = 3}
A reference is a record with one mutable field named contents. You can't really fabricate this up from an arbitrary mutable field of some other record. Even if you are willing to lie to the type system, a field of a record is not represented at all the same as a record.
You could declare your fields as actual references:
type mpoint = { x: int ref; y: int ref; }
Then there is no problem, apoint.x really is a reference. But this representation is not as efficient, i.e., it takes more memory and there are more dereferences to access the values.
If an API is designed in an imperative style it will be difficult to use in OCaml. That's how I look at it anyway. Another way to say this is that ints are small. The interface should perhaps accept an int and return a new int, rather than accepting a reference to an int and modifying it in place.
Jeffrey Scofield explained why this can't be done in ocaml from the point of the type system.
But you can also look at it from the point of the GC (garbage collector). In ocaml internally everything is either a trivial type (int, bool, char, ...) that is stored as a 31/63 bit value or a pointer to a block of memory. Each block of memory has a header that describes the contents to the GC and has some extra bits used by GC.
When you look at a reference internally it is a pointer to the block of memory containing the record with a mutable contents. Through that pointger the GC can access the header and know the block of memory is still reachable.
But lets just assume you could pass apoint.y to a function taking a reference. Then internally the pointer would point to the middle of apoint and the GC would fail when it tries to access the header of that block because it has no idea at what offset to the pointer the header is located.
Now how to work around this?
One way that was already mentioned is to use references instead of mutable. Another way would be to use a getter and setter:
# type 'a mut = (unit -> 'a) * ('a -> unit);;
type 'a mut = (unit -> 'a) * ('a -> unit)
# type mpoint = { mutable x:int ; mutable y: int };;
type mpoint = { mutable x : int; mutable y : int; }
# let mut_x p = (fun () -> p.x), (fun x -> p.x <- x);;
val mut_x : mpoint -> (unit -> int) * (int -> unit) = <fun>
# let mut_y p = (fun () -> p.y), (fun y -> p.y <- y);;
val mut_y : mpoint -> (unit -> int) * (int -> unit) = <fun>
If you only want to incr the variable you can pass an incrementer function instead of getter/setter. Or any other collection of helper functions. A getter/setter pait is just the most generic interface.
You can always copy temporarily the content of field, call the function on that, and back again:
let increment_point_x apoint =
let x = ref apoint.x in
increment x;
apoint.x <- !x
Certainly not as efficient (nor elegant) as it could, but it works.
It is impossible to do exactly what the question asks for (#JeffreyScofield explains why, so I won't repeat that). Some workarounds have been suggested.
Here is another workaround that might work if you can change the implementation of the increment function to use a 'home made' ref type. This comes very close to what was asked for.
Instead of having it take a 'built-in' reference, we can define our own type of reference. The spirit of a 'reference' is something you can set and get. So we can characterise/represent it as a combination of a get and set function.
type 'a ref = {
set: 'a -> unit;
get: unit -> 'a;
};;
type 'a ref = { set : 'a -> unit; get : unit -> 'a; }
We can define the usual ! and := operators on this type:
let (!) cell = cell.get ();;
val ( ! ) : 'a ref -> 'a = <fun>
let (:=) cell = cell.set;;
val ( := ) : 'a ref -> 'a -> unit = <fun>
The increment function's code can remain the same even its type 'looks' the same (but it is subtly 'different' as it is now using our own kind of ref instead of built-in ref).
let increment cell = cell := !cell + 1;;
val increment : int ref -> unit = <fun>
When we want a reference to a field we can now make one. For example a function to make a reference to x:
let xref pt = {
set = (fun v -> pt.x <- v);
get = (fun () -> pt.x);
};;
val xref : mpoint -> int ref = <fun>
And now we can call increment on the x field:
increment (xref apoint);;
- : unit = ()

Having trouble creating arbitrary new Object, parametrized for function call

I wanted this kind of expression in OCaml
let wrapper obj f = fun raw -> f (new obj raw)
But I get a compiler error of Unbound class obj but so what, why isn't the compiler satisfied with creating this function which just says call a function on this object which happens to take one init arg.
Pass a function that constructs the object. For a one-argument class foo you can use new foo to get that function.
let wrapper make_obj f raw = f (make_obj raw)
class foo (x) = object
method y = x + 1
end
let answer = wrapper (new foo) (fun o -> o#y) 2
Here, wrapper has a very general type that doesn't mention objects at all. If you want to make it clear that an object constructor is expected as the argument, you can restrict the type with an annotation:
let wrapper (make_obj: (_ -> < .. >)) f raw = f (make_obj raw)
One way to look at this is that an OCaml class is a type, not a value. So you can't write a function in OCaml that accepts a class as a parameter.
Here's a session:
$ ocaml
OCaml version 4.02.1
# class abc = object method m = 12 end;;
class abc : object method m : int end
# abc;;
Error: Unbound value abc
# let f (x: abc) = x#m ;;
val f : abc -> int = <fun>
# f (new abc);;
- : int = 12
As you can see, abc is a type. Not a value.
In other languages, classes are values. But not in OCaml.

Polymorphic object update in OCaml

I want to achieve a system, where objects are polymorphic over their field's contents and that content can be changed. I.e. an object offers a generic way to exchange field f with value a of type a_t with a value b of type b_t for every field f.
A first attempt would be something like this:
class ['a] not_working (a : 'a) = object
val _a = a
method field_a = _a
method modify_a new_a = {< _a = new_a >}
end
This is not polymorphic enough, as the type of not_working is:
class ['a] not_working : 'a -> object ('b) val _a : 'a method field_a : 'a method modify_a : 'a -> 'b end
i.e. the modification yields an object of the same type.
My workaround is the following:
class ['fields_t] the_class (fields : 'fields_t) = object
method field_a = fields#field_a
method field_b = fields#field_b
end
let modify_field_a instance new_a = new the_class (object method field_a = new_a ; method field_b = instance#field_b end)
let modify_field_b instance new_b = new the_class (object method field_a = instance#field_a ; method field_b = new_b end)
let instance = new the_class (object method field_a = 1 ; method field_b = "foo" end)
let mod_instance = modify_field_a instance "1"
I generate a modification function for every field in the_class and this modification function updates this field and copies all others. This is quite noisy.
Is there a way to use the object copy operator or a comparable construct in a similar manner to reduce the boilerplate?
I don't think that you can do what you're after with objects, as I think that would involve a non-regular recursive type:
type 'a foo = < modify: 'b. 'b -> 'b foo >
Note the error message if you try to define that type:
Characters 4-42:
type 'a foo = < modify: 'b. 'b -> 'b foo >;;
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
Error: In the definition of foo, type 'b foo should be 'a foo
You might have better luck using records (or first-class modules):
# type ('a, 'b) foo = { a: 'a; b: 'b };;
type ('a, 'b) foo = { a : 'a; b : 'b; }
# let new_foo a b = {a; b};;
val new_foo : 'a -> 'b -> ('a, 'b) foo = <fun>
# let modify_a r new_a = { r with a = new_a };;
val modify_a : ('a, 'b) foo -> 'c -> ('c, 'b) foo = <fun>
# let modify_b r new_b = { r with b = new_b };;
val modify_b : ('a, 'b) foo -> 'c -> ('a, 'c) foo = <fun>

Is there a programming language that performs currying when named parameters are omitted?

Many functional programming languages have support for curried parameters.
To support currying functions the parameters to the function are essentially a tuple where the last parameter can be omitted making a new function requiring a smaller tuple.
I'm thinking of designing a language that always uses records (aka named parameters) for function parameters.
Thus simple math functions in my make believe language would be:
add { left : num, right : num } = ...
minus { left : num, right : num } = ..
You can pass in any record to those functions so long as they have those two named parameters (they can have more just "left" and "right").
If they have only one of the named parameter it creates a new function:
minus5 :: { left : num } -> num
minus5 = minus { right : 5 }
I borrow some of haskell's notation for above.
Has any one seen a language that does this?
OCaml has named parameters and currying is automatic (though sometimes type annotation is required when dealing with optional parameters), but they are not tupled :
Objective Caml version 3.11.2
# let f ~x ~y = x + y;;
val f : x:int -> y:int -> int = <fun>
# f ~y:5;;
- : x:int -> int = <fun>
# let g = f ~y:5;;
val g : x:int -> int = <fun>
# g ~x:3;;
- : int = 8
Sure, Mathematica can do that sort of thing.

Resources