Reputation: 99526
in SML, consider side effect by references.
Is it correct that any variable (whether used with or without side effect) denotes a reference which then refers to a value?
is it possible to get the reference denoted by a variable? Is there an operation like &
in C for the same purpose? (In SML, a variable as an expression is by default evaluated not to the reference denoted by the variable, but to the value referred to by the reference denoted by the variable.)
Can an reference be the result from evaluating an expression?
Upvotes: 0
Views: 437
Reputation: 52008
Your first question isn't completely clear. Not all values in SML are ref
types. In val a = 3
, the name a
is bound to an int
rather than an int ref
type. So in that sense the answer is simply "no", not all values in SML are references, most of them are not. On the other hand, it is a bit on an implementation question if under the hood an SML implementation uses references to manage the bindings of names to values.
For your other two questions, given any type 'a
in SML there is a related reference type 'a ref
. You can create values of this type and assign them to variables. Given a value of a ref
type you can dereference it (using the operator !
) to get to the value it refers to (otherwise it would be somewhat useless) and you can return reference types from functions. In fact the function ref
is a polymorphic function which return reference types. See sml - Usage of the ref function.
SML doesn't have an address operator like &
in C, but reference types can be made to refer to the value to which a name is bound.
Given
val a = 4
val b = ref(3)
b is now an int ref
. That b
can be made to refer to the value that a
is bound to:
b := a
Now !b
evaluates to 4
. So in that sense :=
is similar to = &
in C, but it is an implementation detail if under the hood b
was made to point to the same memory location that the value of a
was stored in or if the value was copied to the place where b
was already pointing.
Upvotes: 3