OCaml : module, class & type - class

I have the following code in OCaml that produces the error " Unbound type constructor variable" :
module OrderedVar = struct
type t = variable
let compare v1 v2 = v1#get_name - v2#get_name
end
module VarSet = Set.Make(OrderedVar)
class variable n =
object
val mutable name = n
method get_name = name
end
How can I declare the type "variable" ?
Thank you
edit :
thank you for your answers but my probleme is a bit more difficult. In fact, I have two modules and two classes that "interlaced". Here, I can't declare the classes "variable" and "clause" before the modules, because they need the modules :
module OrderedVar = struct
type t = variable
let compare v1 v2 = v1#get_name - v2#get_name
end
module VarSet = Set.Make(OrderedVar)
module OrderedClause = struct
type t = clause
let compare = compare
end
module ClauseSet = Set.Make(OrderedClause)
class variable n =
object
val mutable name = n
val mutable cpos = ClauseSet.empty
method get_name = name
end
class clause =
object
val mutable vpos = VarSet.empty
end

Declare the variable class before you use it. Order is important in Ocaml unlike typical C based OO languages where the classes and methods can appear anywhere in files.
This quote comes from https://realworldocaml.org/v1/en/html/files-modules-and-programs.html
Unlike C, programs in OCaml do not have a unique main function. When an OCaml program is evaluated, all the statements in the implementation files are evaluated in the order in which they were linked together.

Two comments:
Mostly this is just an ordering problem.
The - operator applies to ints, so I assume your names are ints?
The following compiles for me:
class variable n =
object
val mutable name: int = n
method get_name = name
end
module OrderedVar = struct
type t = variable
let compare v1 v2 = v1#get_name - v2#get_name
end
module VarSet = Set.Make(OrderedVar)
Update
For the new code, the easiest place to break the cycle (it seems to me) is with the class variable. Its visible type is rather simple. The following compiles for me:
type variabletype = < get_name : int >
module OrderedVar = struct
type t = variabletype
let compare v1 v2 = v1#get_name - v2#get_name
end
module VarSet = Set.Make(OrderedVar)
class clause =
object
val mutable vpos = VarSet.empty
end
module OrderedClause = struct
type t = clause
let compare = compare
end
module ClauseSet = Set.Make(OrderedClause)
class variable n =
object
val mutable name: int = n
val mutable cpos = ClauseSet.empty
method get_name = name
end
Maybe this will generalize OK to your actual problem.

Related

F# interface syntax to declare a function with byref returned object (or Tuple), like Int32.TryParse

I'm not able to find how to declare a function in an interface so that I have a Tuple or byref result.
I want to simulate this syntax:
let executed, value = Int32.TryParse("123")
Let's say that I have a function with 2 input parameters and I want to know if the result is successful and in case having the result (a Record type in this case). Kind of:
type Result = {reference:string; value:decimal}
type IExecutor =
abstract member DoStuff: (aa:string) * (bb:string) * (result:byref<Result>) -> bool
abstract member DoStuff: (aa:string, bb:string, result:byref<Result>) -> bool
type Executor () =
member this.DoStuff (aa:string, bb:string, result:byref<Result>):bool =
result <- {reference="ref"; value=0m}
false
let executed, result = executor.DoStuff "aa" "bb"
or
let executed, result = executor.DoStuff("aa", "bb")
I'm not able to declare DoStuff in the interface.
The second try is a copy of the Int32.TryParse signature I see from intellisense, why doesn't work?
What is the correct syntax for having DoStuff called as I want ?
First of all to declare an interface you use abstract members and you only apply the signature
type IExecutor =
abstract member DoStuff: string*string*outref<int>->bool
If you want to implement the interface it goes as follows
type Executor() =
interface IExecutor with
member this.DoStuff (a:string,b:string,result:outref<int>) : bool =
result <- 3
true
You can call it like this
let s = new Executor() :> IExecutor
let a,b = s.DoStuff ( "lorem" "ipsum" )
Having said that, if you're consuming this only from F# avoid outrefs use tuples:
type IExecutor =
abstract member DoStuff: string->string->bool*int
type Executor() =
interface IExecutor with
member this.DoStuff (a:string) (b:string) : bool*int =
true,3
let s = new Executor() :> IExecutor
let a,b = s.DoStuff "lorem" "ipsum"

Nim - Create sequence of objects which implement a method

I want to program a game and would like to use a component pattern for multiple entities.
In a language with interfaces / type-classes / multiple inheritance there would be no problem.
I want some entities to be updateable but not renderable and some shall be both.
Haskell:
class Updateable a where
update :: Float -> a -> a
class Renderable a where
render :: a -> Picture
class InputHandler a where
handleInput :: Event -> a -> a
I can create a list of things that can be updated.
updateAll :: Updateable a => Float -> [a] -> [a]
updateAll delta objs = map (update delta) objs
In Java/D/... this could be implemented via Interfaces
interface Updateable {
void update(float delta);
}
// somewhere in a method
List<Updateable> objs = ...;
for (Updateable o : objs) {
o.update(delta);
}
Now I am wondering how this can be implemented in nim with multimethods.
Can the existence of a fitting multimethod be expressed in a type?
var objs: seq[???] = #[]
Edit: Added more code and fixed incorrect Haskell example
I'm not sure if this answers your question, but it's worth mentioning.
If you were to store you game objects in separate lists based on type, you could still write a lot of generic logic. Storing objects by type has better better performance because of read-ahead and branch prediction. See this lecture, from a guy who should know what he's talking about: Multiprocessor Game Loops: Lessons from Uncharted 2: Among Thieves.
For instance, if you have defined a texture proc for some of your object types, then you can write a generic draw(t: T) = magicRenderToScreen(texture(t)) proc that will work for all of them. This is also useful if you are implementing resource pools, or any kind of general behaviour really.
You do have to include each affected object type in the render and update loops somehow, but that's usually not a big deal in practice. You can even use a simple macro to make this less verbose, so your render loop simply contains something like renderAll(players, enemies, sprites, tiles)
Generic lists are not straightforward in compiled languages, and nim forces you to see it, which is kind of good when you're working on a game. To have generic lists you typically either have to use pointers and dynamic dispatch, or some kind of union type. I seem to remember that nim used to be able to dispatch to the correct multi-methods from parent object ref's, (which would enable lists to contain several types and dispatch dynamically at runtime) but I'm honestly not sure if that can still be done...?
Someone more knowledgeable please let us know!
The lack of an explicit interface keyword is common question in the Nim community. Taking Araq's answer and applying it to a hypothetical case based on your Java/D snippet we could write something like this:
import strutils # For formatFloat
type
IUpdateable =
tuple[
update: proc(v: float) {.closure.},
show: proc(): string {.closure.}
]
Rounded = ref object
internalValue: float
Real = ref object
a_real_value: float
# Here goes our rounded type.
proc `$`(x: Rounded): string =
result = "Rounded{" & $int(x.internalValue) & "}"
proc updateRounded(x: Rounded, delta: float) =
x.internalValue += delta
proc getUpdateable(x: Rounded): IUpdateable =
result = (
update: proc(v: float) = x.updateRounded(v),
show: proc(): string = `$`(x)
)
converter toIUpdateable(x: Rounded): IUpdateable =
result = x.getUpdateable
# Here goes our Real type.
proc `$`(x: Real): string =
result = "Real{" &
x.a_real_value.format_float(precision = 3) & "}"
proc update_real(x: Real, delta: float) =
x.a_real_value += delta
proc getUpdateable(x: Real): IUpdateable =
result = (
update: proc(v: float) = x.update_real(v),
show: proc(): string = `$`(x)
)
# Here goes the usage
proc main() =
var objs: seq[IUpdateable] = #[]
var a = Rounded()
var b = Real()
a.internalValue = 3.5
b.a_real_value = 3.5
objs.add(a) # works because of toIUpdateable()
objs.add(b.getUpdateable)
for obj in objs:
echo "Going through one loop iteration"
echo "\t", obj.show()
obj.update(0.4)
echo "\t", obj.show()
obj.update(0.4)
echo "\t", obj.show()
main()
# -> Going through one loop iteration
# -> Rounded{3}
# -> Rounded{3}
# -> Rounded{4}
# -> Going through one loop iteration
# -> Real{3.50}
# -> Real{3.90}
# -> Real{4.30}
However, as you can read in that forum thread, depending on what exactly you need interfaces for other approaches may be better. Also, presumably the future way to go are concepts, but as usual the manual is dry and the related unit tests are cryptic so I couldn't manage to translate the previous tuple example to concepts.
If you feel like going for concepts you should ask in the forum directly, but beware, as the manual says, concepts are still in development.
Swift has the same problem and there they use Type Erasure, which is the same as proposed in the previous comments but a bit more strutured. The general pattern in Nim is like this:
#-------------------------------------------------------------
# types
#-------------------------------------------------------------
type C = concept type C
proc name(x: C, msg: string): string
type AnyC = object
name: proc(msg: string): string # doesn't contain C
type A = object
type B = object
#-------------------------------------------------------------
# procs
#-------------------------------------------------------------
proc name(x: A, msg: string): string = "A" & msg
proc name(x: B, msg: string): string = "B" & msg
proc name(x: AnyC, msg: string): string = x.name(msg) # AnyC implements C
proc to_any(x: A): AnyC = AnyC(
name: proc (msg: string): string = name(x, msg) # x captured by proc
)
proc to_any(x: B): AnyC = AnyC(
name: proc (msg: string): string = name(x, msg) # x captured by proc
)
# actually use C
proc print_name(x: C, msg: string) = echo x.name(msg)
#-------------------------------------------------------------
# main
#-------------------------------------------------------------
let a = A()
let b = B()
let cs = [a.to_any(), b.to_any()] # the main goal of most erasure cases
for c in cs:
c.print_name(" erased") # e.g. "A erased"
In this example AnyC implements C, A and B also implement C but more importantly can be converted to AnyC. The Any* types usually contain closures to effectively erase the type and also implement the concept itself by trivial forwarding the arguments.
I wish there was a macro or something that would implement Any* and to_any automatically.

How to get a reference to a string in Scala and modify the original string by modifying this reference?

As I understand, strings in Scala are value types:
var a = "hello"
var b = a
b = "hi"
-
println(a) // hello
println(b) // hi
I want a to point to b and make code above print
hi
hi
Is this possible?
Warning: This is very bad functional style
Your a and b are strings. What you want is a reference to a string!
class StringRef(var s:String)
val a = new StringRef("hello")
val b = a
b.s = "Hi"
println(a.s) // Hi
println(b.s) // Hi
You can't do this because in Java/Scala everything is assigned-by-value. You can't assign a variable to directly reference another variable.
Instead you can assign both variables to contain the same reference value to a mutable object.

Does Scala have record update syntax for making modified clones of immutable data structures?

In Mercury I can use:
A = B^some_field := SomeValue
to bind A to a copy of B, except that some_field is SomeValue instead of whatever it was in B. I believe the Haskell equivalent is something like:
a = b { some_field = some_value }
Does Scala have something like this for "modifying" immutable values. The alternative seems to be to have a constructor that directly sets every field in the instance, which isn't always ideal (if there are invarients the constructor should be maintaining). Plus it would be really clunky and much more fragile if I had to explicitly pass every other value in the instance I want to have a modified copy of.
I couldn't find anything about this by googling, or in a brief survey of the language reference manual or "Scala By Example" (which I have read start-to-finish, but haven't absorbed all of yet, so it may well be in there).
I can see that this feature could have some weird interactions with Java-style access protection and subclasses though...
If you define your class as a case class, a convenient copy method is generated, and calling it you can specify with named parameters new values for certain fields.
scala> case class Sample(str: String, int: Int)
defined class Sample
scala> val s = Sample("text", 42)
s: Sample = Sample(text,42)
scala> val s2 = s.copy(str = "newText")
s2: Sample = Sample(newText,42)
It even works with polymorphic case classes:
scala> case class Sample[T](t: T, int: Int)
defined class Sample
scala> val s = Sample("text", 42)
s: Sample[java.lang.String] = Sample(text,42)
scala> val s2 = s.copy(t = List(1,2,3), 42)
s2: Sample[List[Int]] = Sample(List(1, 2, 3),42)
Note that s2 has a different type than s.
You can use case classes for this, but you don't have to. Case classes are nothing magical - the modifier case just saves you a lot of typing.
The copy method is realized by the use of named and default parameters. The names are the same as the fields and the defaults are the current values of the fields. Here's an example:
class ClassWithCopy(val field1:String, val field2:Int) {
def copy(field1:String = this.field1, field2:Int = this.field2) = {
new ClassWithCopy(field1,field2);
}
}
You can use this just like the copy method on case classes. Named and default parameters are a very useful feature, and not only for copy methods.
If the object you're planning on modifying is a case class then you can use the autogenerated copy method:
scala> val user = User(2, "Sen")
user: User = User(2,Sen)
scala> val corrected = user.copy(name = "Sean")
corrected: User = User(2,Sean)

OCaml types with different levels of specificity

I am attempting to simulate an interface in OCaml and am using the "type" construct. I have two types:
type fooSansBar = {a: string; b: int};;
type fooConBar = {a:string; b:int; bar:char};;
...and would like to define a particular fooSansBar:
let fsb = {a="a"; b=3};;
...but am told that the bar field is not defined. From this, it appears that, contrary to the values I passed in matching fooSansBar's signature, the system believes I am trying to create a fooConBar. Is it possible to create a fooSansBar if the two types as defined above exist?
Additionally (because I'm new to OCaml) is there a better way to simulate an interface?
In OCaml, field names in record types must be unique, so the two types you define cannot coexist simultaneously. Caml is the only language I know with this property.
Because the second definition hides the first, when the compiler sees the a and b fields it expects them to belong to the fooConBar type and so complains of the missing bar field.
If you are trying to simulate an interface, the correct functional way to do it in Caml is to define a module type.
module type FOO_CON_BAR = sig
val a : string
val b : int
val bar : char
end
And an instance:
module Example = struct
let a = "hello"
let b = 99
let c = '\n'
end
With modules and module types you also get subtyping; there's no need to resort to objects.
P.S. My Caml is rusty; syntax may be off.
There are several possible solutions in OCaml depending how you're using the code you gave. The simplest is to combine the two types:
type fooBar = { a: string; b: int; bar: char option }
Another solution is to replace the records with objects because objects support subtyping (and can have their types inferred so there is no need to declare a type!):
# let fsb = object
method a = "a"
method b = 3
end;;
val fsb : < a : string; b : int > = <obj>
# fsb#a, fsb#b;;
- : string * int = ("a", 3)
The second type redefines a and b, effectively hiding the first, which is why it cannot be constructed any more. You could define these types in different modules, but that would be the same as using a different name for a and b.
These constructs can only be used when you do not try to "derive" from another interface, but just implement it.
If you wish to use these object oriented concepts in Ocaml, you could look at the object system, or, depending on your problem, the module system. Alternatively, you could try to solve your problem in a functional way. What problem are you trying to solve?
OCaml provides two ways to implement interfaces. One, as already mentioned, is a module type.
The other is a class type. You can write a class type (interface) fooSansBar:
class type fooSansBar = object
method a: string
method b: int
end
and a class type fooConBar:
class type fooConBar = object
inherit fooSansBar
method bar: char
end
This will allow you to use a fooConBar anywhere a fooSansBar is required. You can now create a fooSansBar, using type inference:
let fsb = object
method a = "a"
method b = 3
end
Now, fsb's type happens to be <a: string; b: int>, as indicated by Jon, but it's perfectly usable as a fooSansBar due to OCaml's structural subtyping.
In OCaml, it's not possible to have two record types with intersecting field sets present in the same scope.
If you really need to use record types with intersecting field sets, then you can work around this restriction by enclosing the types within their own dedicated modules:
module FooSansBar = struct type t = {a:string; b:int} end
module FooConBar = struct type t = {a:string; b:int; bar:char} end
Then you can construct instances of these types like so:
let fsb = {FooSansBar.a="a"; b=3}
let fcb = {FooConBar.a="a"; b=4; bar='c'}
These instances have the following types:
fsb : FooSansBar.t
fcb : FooConBar.t