About Monkey 2 › Forums › Monkey 2 Programming Help › Tuple experiment and usages
This topic contains 16 replies, has 5 voices, and was last updated by
Diffrenzy
1 year, 6 months ago.
-
AuthorPosts
-
September 26, 2017 at 10:14 am #10820
This is a small experiment to test how tuples can be implemented and be used. Tuples can be used in some cases where you want data representations without going into specific concrete class implementations.
In other scripting languages such as Python tuples are merged into lists, where due to duck typing you get no datatype collisions. This means you can do this: item = [“position”, 100, 200, 300]. In strict languages you will need to take type safety into consideration so you will need to wrap this concept around a concrete implementation. Such as: Local tuple:Tuple4 = Tuple.Create(“position”, 100, 200, 300)
Another example
If you want to represent a bullet in your game you only need to know the spawnerID (who fired it) and it’s location (three numbers), a Tuple4. All of the other data can be reused from global variables (the image, the size, etc).Also in some other occasions you need to split your code logic into separate places. For example when you load a level you do the parsing of the file that involves file system operations and the level initialization where you generate data to be placed in lists and arrays. At the parsing stage you can use a Tuple3 to place the tileID and position as a temporary representation, at the initialization stage you can convert the raw Tuple3 data into proper classes.
Another example when you have a function that needs to return two results instead of one. Instead of having a return signature of Bool it can have a Tuple2 with Bool and Integer.
Monkey1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283#Import "<std>"Using std..Class TuplePrivateMethod New()EndPublicFunction Create<T1, T2>:Tuple2<T1, T2>(t1:T1, t2:T2)Local tuple := New Tuple2<T1, T2>tuple.Item1 = t1tuple.Item2 = t2Return tupleEndFunction Create<T1, T2, T3>:Tuple3<T1, T2, T3>(t1:T1, t2:T2, t3:T3)Local tuple := New Tuple3<T1, T2, T3>tuple.Item1 = t1tuple.Item2 = t2tuple.Item3 = t3Return tupleEndFunction Create<T1, T2, T3, T4>:Tuple4<T1, T2, T3, T4>(t1:T1, t2:T2, t3:T3, t4:T4)Local tuple := New Tuple4<T1, T2, T3, T4>tuple.Item1 = t1tuple.Item2 = t2tuple.Item3 = t3tuple.Item4 = t4Return tupleEndMethod To:String() VirtualReturn ""EndEndClass Tuple2<T1, T2> Extends TupleField Item1:T1Field Item2:T2Method To:String() OverrideReturn "Tuple: "+Item1+", "+Item2EndEndClass Tuple3<T1, T2, T3> Extends TupleField Item1:T1Field Item2:T2Field Item3:T3Method To:String() OverrideReturn "Tuple: "+Item1+", "+Item2+", "+Item3EndEndClass Tuple4<T1, T2, T3, T4> Extends TupleField Item1:T1Field Item2:T2Field Item3:T3Field Item4:T4Method To:String() OverrideReturn "Tuple: "+Item1+", "+Item2+", "+Item3+", "+Item4EndEndFunction Main()' create tuples on the fly to represent data structures' place them on the listLocal items := New List<Tuple>' use the factory functions for great ease of useitems.Add(Tuple.Create("Entity", 123))items.Add(Tuple.Create("Size", 50, 50))items.Add(Tuple.Create("Position", 200, 0, 100))Print("Print List Of Tuples")For Local i := Eachin itemsPrint(i)NextEndFor anyone that interested into technical details:
In this first iteration I used concrete classes for representing tuples: Tuple2, Tuple3, Tuple4.
The code can be extended up to Tuple10 which is an extreme case, I doubt if greater than Tuple4 will be needed, but just for the sake of it, it can happen.September 27, 2017 at 5:07 am #10825Cool!
Some time ago I added issue on github about creating tuples with same name (like in c#):
- Tupple<T1,T2>
- Tupple<T1,T2,T3>
- Tupple<T1,T2,T3,T4>
We can’t do it in monkey – it produce duplicate identifier error . I don’t know is it good to be implemented in monkey2 language.
I’d be happy with Tupple2,3,4,… too.
September 27, 2017 at 6:19 pm #10845Did you do the the same implementation more or less?
If you have any ideas for improvements let me know.
September 27, 2017 at 10:21 pm #10850I have been thinking about tuples a bit lately, and I actually think adding tuples directly to the language itself would not be *that* tricky – well, the syntax side of things anyway.
Basically, anything in brackets would be a tuple, eg: (1), (10,”Hello”,arseBisuits) etc.
A single element tuple would be interchangeable with a simple value/expression.
Tuple types could be declared with brackets, eg: Local result:(Entity,bool), Function Find:(Object,bool)( blah:String ) etc.
Nested tuples would simply be collapsed/linearized, eg: (10,20,(30,40)) and (10,20,30,40) would have the sample type: (Int,Int,Int,Int).
Tuple initializers: Local (x,y,z):=(10,”Hello”,.5), Local (x:Int,y:String,z:Float)=(10,”Hello”,.5)
Tuple assignments: (x,y,z)=(1,2,3), (x,y,z)+=(10,20,30)
Tuple operators: (x,y,z)+(10,20,30)
These all seem quite intuitive to me and should be relatively easy to parse, although actual backend implementation etc would be challenging.
Definitely not gonna happen in the near future, but worth thinking about.
(Ok, type conflicts with function types (I think) – perhaps <> instead, eg: Local x:<Int,Float>?)
September 28, 2017 at 4:47 am #10852Tuple types could be declared with brackets, eg: Local result:(Entity,bool), Function Find:(Object,bool)( blah:String ) etc.
It would be super-cool!
Ok, type conflicts with function types (I think) – perhaps <> instead, eg: Local x:<Int,Float>?
But < > are used for templates types, conflictable too.
I prefer ( ) because other langs use them.
September 28, 2017 at 7:20 pm #10862I prefer ( ) because other langs use them.
Examples?
I’m especially interested in statically typed languages. I’m vaguely aware of how python does tuples, but that doesn’t really have type declarations.
September 28, 2017 at 7:44 pm #10864I’d personally suggest an unused character like {} for example. It’s the chars used for defining sets in math notation so it’s kind of relevant to me.
September 29, 2017 at 4:10 am #10873Examples?
C# 7.0: http://www.c-sharpcorner.com/article/working-with-value-tuple-in-c-sharp-7-0/
Swift: https://www.weheartswift.com/tuples-enums/
Kotlin (not a tuple, but..): http://kotlinlang.org/docs/reference/multi-declarations.html
(I like Kotlin lang, advice to take a look.)
What about don’t wrap returned type with any chars and use just a commas?
Monkey12345678Function NewGenFunc: Stack<View>,Int( source:Map<String,View> )Local stack:=New Stack<String>' do somethingLocal specialCount:=CalcCount( source )Return (stack,specialCount)EndSeptember 29, 2017 at 5:06 am #10876Thanks for that, will do some reading!
I don’t actually think ‘()’ would be a problem after all. Comma separated list of types would be trickier due to ‘,’ in Local, Global etc decls, esp. if ‘named’ tuple members are allowed.
October 2, 2017 at 9:05 pm #10939This would be very nice if they are added to the language. Thanks Mark.
My estimation on this, is that in the first step, tuples would be used to model interesting structured arrays – which is the essential part. The next step would be how these tuples can managed in terms of usage and syntax such as initialization, assignments, operations – which are language constructs for ease of use.
My approach on this would be to implement Tuples as library and not as language constructs, because this can introduce competing paradigms. This way you will be able to do tuple things but in a more controlled fashion, the bounds will be clear and they can be accessed through the library.
Languages as Swift or Kotlyn have functional concepts embedded in them so they need tuples in more fundamental levels, The FP paradigm assumes to abstract datatypes from functions and rely on type signatures instead. Tuples are used to signify the type signatures. Where in Monkey2 I don’t think that there is such to go too functional, the program designs can be managed differently, as OO or modular.
Monkey1234567instead of writing:var a = 1var b = 2var c = 3you can write:var (a, b, c) = (1, 2, 3)October 5, 2017 at 8:48 am #10984Swifts named tuple elements, that you can access via dot notation looks super cool.
Tuples seems very suitable for game object properties, and would be incredibly useful when deserializing from text (eg xml) , especially if there was a way to specify to what attributes should be deserialized.
XML Example : <myobject name=”awsomeobject” x=”20″ y=”30″ color=”#d40053″ factor=”2.33456″/>
In the above I’d like a way to specify ( in a shared map or something) that “name” is a string, “x”,”y” are Ints, “factor” is Float and “color” should be sent to a Color Ctor that takes the Hex color as input, Then I’d like it to become a Tuple, myTupple:<String,Int,Int,Color,Float>
To add to the awesomeness, then address the values with dot notation, like this:
Print myTupple.name + “has color ” + myTupple.color
Btw: Can we use the syntax for generics: Local myt:Tuple<Int,Float,MyType,etc> ?
October 5, 2017 at 8:55 am #10985Can we use the syntax for generics: Local myt:Tuple<Int,Float,MyType,etc> ?
Yes, if you write own class realization.
But it’s not our case.
There are should be code like that for named tuples:
myTupple:<name:String, x:Int, y:Int, color:Color, factor:Float>
Ps: in swift tuples is value-typed (like structs in monkey2), so when you assign them you got new instance:
Monkey1234567var someScore = ("John", 55)var anotherScore = someScoreanotherScore.0 = "Robert"println(anotherScore.0) //Outputs: "Robert"println(someScore.0) //Outputs: "John"October 5, 2017 at 9:11 am #10986myTupple:<name:String, x:Int, y:Int, color:Color, factor:Float>
looks nice, could be
myTupple:Tuple<name:String, x:Int, y:Int, color:Color, factor:Float>
I don’t understand the reason for not writing the type name.
More importantly: How to deserialise? Currently I’m using a rather ugly “parametercollection” for bundles of related parameters, that has a “FromXMLNode()”, but Tuples seems much better.
I’m thinking that Marks “UniformBlock” might be there for the same reason. If so it could be replaced by Tuples.
[EDIT] : UniformBlock seems to be a OpenGL thingy ?
October 5, 2017 at 9:40 am #10987More importantly: How to deserialise?
And how to serialize too.
Don’t know is it possible to reflect(-ion) tuples at all to make them serializable.
October 5, 2017 at 9:47 am #10988And how to serialize too.
They seem like prime candidates!
A Tuple should be able to have a ToString(), just like other objects.
In that, loop through the elements using their name and type, calling objects ToString()/ToXml() method when needed.
So I guess I’m thinking a Tuple should have a For eachin me iterator.
-
AuthorPosts
You must be logged in to reply to this topic.