{"id":2416,"date":"2016-05-01T10:12:01","date_gmt":"2016-04-30T22:12:01","guid":{"rendered":"https:\/\/www.deltics.co.nz\/blog\/?p=2416"},"modified":"2016-05-02T08:45:00","modified_gmt":"2016-05-01T20:45:00","slug":"relight-my-fire","status":"publish","type":"post","link":"https:\/\/www.deltics.co.nz\/blog\/posts\/2416\/","title":{"rendered":"Relight My Fire"},"content":{"rendered":"<span class=\"rt-reading-time\" style=\"display: block;\"><span class=\"rt-label rt-prefix\">[Estimated Reading Time: <\/span> <span class=\"rt-time\">7<\/span> <span class=\"rt-label rt-postfix\">minutes]<\/span><\/span><p>I&#8217;m not sure how many more song inspired Fire references I can keep coming up with, but here at least is one more.<\/p>\n<p><!--more--><\/p>\n<p>In response to <a href=\"https:\/\/www.deltics.co.nz\/blog\/posts\/2393\">my previous post<\/a> Wouter commented that he had a much simpler cross platform solution to the random number problem:<\/p>\n<pre class=\"brush: delphi; title: ; notranslate\" title=\"\">\r\nprogram random;\r\nbegin\r\n  Randomize;\r\n  Writeln(random);\r\nend.\r\n<\/pre>\n<p>Which is very pithy but actually makes a very good point for me, one which I was coming to anyway.<\/p>\n<p>Pascal is, as it were, one of the old guard in the programming language battalion.  And in particular the earliest implementations were extremely simple, relative to modern languages, intended (famously) to teach programming.  That is, programming in the state of the art as <em>current at the time<\/em>.<\/p>\n<p>Modern Pascal dialects actually have very little in common with those early incarnations of Pascal whilst the platforms on which those dialects run have become significantly more complex (and capable).<\/p>\n<p>Yet, as simple as it is, the simple code above does not compile in Oxygene.<\/p>\n<p>Surely a major shortcoming ?<\/p>\n<p>Well, only if you intend to neglect the capabilities of the modern platforms on which your code runs today.<\/p>\n<p>A lot of things that a Pascal developer might take for granted in the Pascal RTL are simply not present in Oxygene.  In much the same way that many parts of the ANSI C RTL are not present in C# (or, more accurately, .NET).  Or rather, the equivalent, modern capabilities <em>are<\/em> present but not in a <em>syntactically compatible<\/em> form.<\/p>\n<h2> .NET Random vs Objective-C Randomness <\/h2>\n<p>I promised last time that the next thing we would do would be to implement a .NET version of the simple <strong>RandomNumber<\/strong> program, re-using the shared code we created to contain a cross platform <strong>RandomNumber<\/strong> generator class.  However, there is a problem we need to address first.<\/p>\n<p>Anyone familiar with random number generation on .NET or Java should have seen it coming.<\/p>\n<p>I had said that the shared <strong>RandomNumber<\/strong> class only needed to provide <em>class<\/em> methods.  And this was true whilst we were exposing (essentially) global functions for seeding a global PRNG and generating random numbers from it.<\/p>\n<p>But in .NET, there are no such global functions.  There is instead a <a href=\"https:\/\/msdn.microsoft.com\/en-us\/library\/system.random(v=vs.110).aspx\">Random<\/a> class which must be instantiated.  The same is also true in Java.<\/p>\n<p>But this is not quite the inconvenience it might first seem.  There are some benefits.<\/p>\n<p>For example, it means you can have multiple independent random number sequences, even with their own independent seeds.  Why would you want to do this ?  Why would you even want multiple random number generators operating independently let alone with different predictable (or unpredictable) sequences ?<\/p>\n<p>I honestly don&#8217;t know.  But I can imagine a scenario in a game, for example, where you might want a predictable sequence of random numbers involved in generating level layouts, so that a player would always get the same layout for each level in turn.  But at the same time you might then want a &#8220;more random&#8221; sequence to trigger events during the game so that the gameplay was not replicated each time those predictable level layouts were played.<\/p>\n<p>But that&#8217;s just a plausible use case.  Not one I&#8217;ve personally used or even come across.<\/p>\n<p>In any event, my initial shared <strong>RandomNumber<\/strong> class is currently not fit for that potential purpose.  So let&#8217;s fix that.<\/p>\n<p>Since we are looking to achieve a uniform programming &#8220;surface&#8221; on the class, I shall model my revised implementation on (a sub-set of) the .NET class.  Checking against the Java <a href=\"https:\/\/docs.oracle.com\/javase\/7\/docs\/api\/java\/util\/Random.html\">Random<\/a> class (same name, different platform) I find that this has almost identical methods to support the interface I have in mind.<\/p>\n<p>Specifically, I shall have a parameterless constructor which shall seed using the current time, another constructor which accepts an integer seed and finally a method to generate and return a random number limited to an integer range:<\/p>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\r\n  type\r\n    RandomNumber = public class\r\n    public\r\n      constructor;\r\n      constructor(seed: Integer);\r\n      method Next(limit: Integer): Integer;\r\n    end;\r\n<\/pre>\n<p>First, let&#8217;s get this working for <strong>NOUGAT<\/strong>.  That is OS X.<\/p>\n<p>It turns out that those global functions (<strong>random()<\/strong> and <strong>srandom()<\/strong>) can be used in conjunction with a state buffer to manage multiple, independent PRNG&#8217;s.<\/p>\n<p>All we need is a buffer to maintain the state for each PRNG and ensure that we apply the applicable state prior to generating numbers (using <strong>setstate()<\/strong>).<\/p>\n<p>The state buffer is simply a suitably dimensioned <strong>AnsiChar<\/strong> array.  The state buffer is initialised before use (with <strong>initstate()<\/strong>) part of which involves providing the seed.  Since each instance of our class shall represent a discrete PRNG, we just need a member variable to hold that state buffer and appropriate initialisation of the buffer in the constructors.  We might as well go ahead and also implement the Next() method while we&#8217;re at it, applying the instance state before generating the random number:<\/p>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\r\n  type\r\n    RandomNumber = public class\r\n    private\r\n      fState: array[256] of AnsiChar;\r\n    public\r\n      constructor;\r\n      constructor(seed: Integer);\r\n      method Next(limit: Integer): Integer;\r\n    end;\r\n\r\nimplementation\r\n\r\n  constructor RandomNumber;\r\n  begin\r\n    constructor(Integer(time(NIL)));\r\n  end;\r\n\r\n  constructor RandomNumber(seed: Integer);\r\n  begin\r\n    initstate(seed, @fState, length(fState));\r\n  end;\r\n\r\n  method RandomNumber.Next(limit: Integer): Integer;\r\n  begin\r\n    setstate(@fState);\r\n    result := Integer(Random mod limit) + 1;\r\n  end;\r\n\r\n<\/pre>\n<p>You may notice this time &#8211; for clarity &#8211; I have not mixed-in the conditional compilation for the other platforms (<strong>ECHOES<\/strong> or <strong>COOPER<\/strong>). Instead let&#8217;s look at the complete implementation for each of those separately.\t \t <\/p>\n<p>To implement these in both cases I shall use a feature, unique to the Elements languages: <a href=\"https:\/\/docs.elementscompiler.com\/Concepts\/MappedTypes\/\">Mapped Types<\/a>.\t \t <\/p>\n<h2>Mapped Types<\/h2>\n<p>A Mapped Type does not create a new distinct type. Instead it creates a synonym or alias for some other type. This is not a &#8216;wrapper&#8217;. The compiler is simply directed that whenever it encounters a reference to a certain type it should instead treat it as a reference to the other, mapped type. This means that you can write your code using the types you have declared in platform independent code, but if you need to pass the objects to some platform specific API you can do so, directly. No need for conversions or wrappers.\t \t <\/p>\n<p>Similarly, within the Mapped Type you can declare methods and map <em>those<\/em> onto methods in the type being mapped on to. Again, these are not wrapper methods. When the compiler encounters a call to the declared method in the type it instead generates a call as specified in the &#8220;map&#8221; to the mapped type.\t \t <\/p>\n<p>A mapped type is similar to a helper or extension class in that it cannot introduce new member data, but it can introduce new methods.\t \t <\/p>\n<p>So with all that in mind let&#8217;s look at the <strong>ECHOES<\/strong> and <strong>COOPER<\/strong> versions of <strong>RandomNumber<\/strong>.\t \t <\/p>\n<h2>ECHOES (.NET)<\/h2>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\t \t \r\n\r\n    RandomNumber = public class mapped to Random\t \t \r\n      constructor; mapped to constructor;\t \t \r\n      constructor(seed: Integer); mapped to constructor(seed);\t \t \r\n      method Next(limit: Integer): Integer; mapped to Next(limit);\t \t \r\n    end;\t \t \r\n\r\n<\/pre>\n<p>This goes in the <strong>interface<\/strong> section. There is no implementation required in this case, at all. The class maps on to the <strong>System.Random<\/strong> class and since this is the model for my mapped type, all of the required methods already exist in the mapped type, but I still need to declare the mappings for those. \t \t <\/p>\n<p>When I reference <strong>RandomNumber<\/strong> I am only able to call the methods declared in the mapped type declaration, otherwise I could inadvertently create platform specific code, defeating the purpose of using a mapped type in the first place.\t \t <\/p>\n<p>The exception to that are any methods on the platform specific base object class which have to be available.\t \t <\/p>\n<p>So, what about the COOPER (Java) version ?\t \t <\/p>\n<h2>COOPER (Java)<\/h2>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\t \t \r\n    RandomNumber = public class mapped to Random\t \t \r\n      constructor; mapped to constructor;\t \t \r\n      constructor(seed: Integer); mapped to constructor(seed);\t \t \r\n      method Next(limit: Integer): Integer; mapped to nextInt(limit);\t \t \r\n    end;\t \t \r\n<\/pre>\n<p>This is almost identical to the .NET mapping. The constructors are identical and provide the same initialisation. The only difference is that the method for obtaining a new, limited range integer is called <strong>nextInt<\/strong>, rather than <strong>Next<\/strong>, so this is addressed in the mapping.\t \t <\/p>\n<h2>Bringing It All Together<\/h2>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\t \t \r\n\r\n    {$if NOUGAT}\t \t \r\n \t \t \r\n      RandomNumber = public class\t \t \r\n      private\t \t \r\n        fState: array[256] of AnsiChar;\t \t \r\n      public\t \t \r\n        constructor;\t \t \r\n        constructor(seed: Integer);\t \t \r\n        method Next(limit: Integer): Integer;\t \t \r\n      end;\t \t \r\n\r\n    {$else}\t \t \r\n\r\n      RandomNumber = public class mapped to Random\t \t \r\n        constructor; mapped to constructor;\t \t \r\n        constructor(seed: Integer); mapped to constructor(seed);\t \t \r\n        method Next(limit: Integer): Integer; mapped to {$if     ECHOES} Next(limit);\t \t \r\n                                                        {$elseif COOPER} nextInt(limit);\t \t \r\n                                                        {$endif} \r\n      end;\t \t \r\n\r\n    {$endif}\t \t \r\n\r\n<\/pre>\n<p>On NOUGAT we declare a new class which provides us with separate PRNG implementations.\t \t <\/p>\n<p>On ECHOES and COOPER we have a class with the same name but which in these cases is merely a synonym for the existing classes on those platforms that already provide the separate PRNGs. Notice that the class name being mapped to is <strong>Random<\/strong> in both cases, with the appropriate namespace identified in the <strong>uses<\/strong> clause.\t \t <\/p>\n<p>On all platforms the programming surface on the class is identical, allowing us to use this class in cross-platform code but still generating direct, native code in each case without the need for wrappers.\t \t <\/p>\n<p>But now, whatever platform I am working on, if ever I need a random number I have a completely consistent and uniform mechanism for doing so, supporting the capabilities of the most capable platform (discrete PRNGs), not reduced to the lowest common denominator (a single, global PRNG).\t \t <\/p>\n<h2>Sweetening the Pill<\/h2>\n<p>Isn&#8217;t this all rather a lot of work just for getting random numbers ?\t \t <\/p>\n<p>Firstly &#8211; not really. I am labouring numerous points here for the purposes of illustration. As you can see, the actual work involved borders on the trivial.\t \t <\/p>\n<p>Secondly &#8211; I&#8217;m making more work for myself that I need to, again for the purposes of illustration.\t \t <\/p>\n<p>There is an open source library for Elements containing a large number of mapped types and other cross-platform helpers. It is called <strong>Sugar<\/strong>, it&#8217;s <a href=\"https:\/\/github.com\/remobjects\/sugar\">hosted on github<\/a> and indeed it already contains a class for random numbers (though it actually takes a different approach to my example).\t \t <\/p>\n<p>So, just one last thing to do before we can move on to creating the .NET and Android apps to use this facility.\t \t <\/p>\n<h2>Refactoring the NOUGAT UI<\/h2>\n<p>We need a reference to an instance of <strong>RandomNumber<\/strong>, so we&#8217;ll add that to our private members. We can only generate random numbers when this reference is assigned, so I will ensure that the <strong>Generate<\/strong> button is initially disabled and only enable it when the <strong>Seeded<\/strong> button is pressed (which will instantiate the <strong>RandomNumber<\/strong>).\t \t <\/p>\n<p>Since I&#8217;ll need to change the state of the button at runtime, I now also need a reference to that button so I add an outlet for that as well, connected to the appropriate button in Xcode Interface Builder:\t \t <\/p>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\t \t \r\n  private\t \t \r\n    fRandom: RandomNumber;\t \t \r\n    [IBOutlet] lblNumber: NSTextField;\t \t \r\n    [IBOutlet] btnGenerate: NSButton;\t \t \r\n    [IBAction] method seed(Sender: id);\t \t \r\n    [IBAction] method generate(Sender: id);\t \t \r\n<\/pre>\n<p>&#8220;Seed&#8221;ing now means instantiating a new <Strong>RandomNumber<\/strong> using the parameterless constructor, so we modify the <strong>seed()<\/strong> action method accordingly and also enable the generate button:\t \t <\/p>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\t \t \r\n    fRandom := new RandomNumber;\t \t \r\n    lblNumber.stringValue := 'Generator Seeded';\t \t \r\n    btnGenerate.enabled := true;\t \t \r\n<\/pre>\n<p>And finally of course, the <strong>generate()<\/strong> action needs to be modified to obtain a value from the current <strong>fRandom<\/strong>:\t \t <\/p>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\t \t \r\n    lblNumber.intValue := fRandom.Next(100);\t \t \r\n<\/pre>\n<p>Done.\t \t <\/p>\n<p>So next time we&#8217;ll build the .NET <strong>and<\/strong> the Android app and see how we use Fire in those cases.<\/p>\n<h2>Footnote on Cryptographic RNG<\/h2>\n<p>None of the above deals with cryptographic RNG&#8217;s. But the same technique could easily be employed to create a <strong>CryptoRNG<\/strong> class to provide a cross-platform class for the cryptograhic RNG capabilities of each platform.<\/p>\n","protected":false},"excerpt":{"rendered":"<p><span class=\"rt-reading-time\" style=\"display: block;\"><span class=\"rt-label rt-prefix\">[Estimated Reading Time: <\/span> <span class=\"rt-time\">7<\/span> <span class=\"rt-label rt-postfix\">minutes]<\/span><\/span> I&#8217;m not sure how many more song inspired Fire references I can keep coming up with, but here at least is one more.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":[]},"categories":[205,4,242,204,180],"tags":[299,181],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p1TKYv-CY","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":1224,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/1224\/","url_meta":{"origin":2416,"position":0},"title":"Sugary Goodness in &#8220;Nougat&#8221;","date":"13 Sep 2012","format":false,"excerpt":"Continuing the theme of recent - and upcoming - posts about new (and not so new) syntax in modern (and not so modern) variations on the Pascal language, I just have to comment on what I regard as yet another stunningly good job that the guys at RemObjects have done\u2026","rel":"","context":"In &quot;Delphi&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2624,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/2624\/","url_meta":{"origin":2416,"position":1},"title":"Expressive If and Case &#8230;","date":"25 Apr 2017","format":false,"excerpt":"A quick post on a small but hugely useful little language feature in Oxygene... if expressions. Many people will be familiar with the so-called ternary operator. Delphi developers will also be aware that there is no direct equivalent in Delphi. In 'C' and other languages we can write a statement\u2026","rel":"","context":"In &quot;Delphi&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1713,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/1713\/","url_meta":{"origin":2416,"position":2},"title":"How to Call Java Code from an Oxygene Android Application","date":"20 Sep 2013","format":false,"excerpt":"Lachlan just posted a link to a post on Google+ (also available as a PDF) demonstrating how to call Java from Delphi XE5. I was shocked at both the amount and the nature of the code involved. It is long, convoluted and ugly stuff (nb. that isn't a criticism of\u2026","rel":"","context":"In &quot;Android&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1882,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/1882\/","url_meta":{"origin":2416,"position":3},"title":"Not Your Grand-Daddy&#8217;s Pascal (or Java)","date":"15 Oct 2013","format":false,"excerpt":"I've mentioned some of the cool stuff in the Oxygene language in various posts and thought it would be a good idea to list them again, along with some others that I've not previously mentioned. Oxygene Everywhere First some of the core language features that are available on all supported\u2026","rel":"","context":"In &quot;Android&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1817,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/1817\/","url_meta":{"origin":2416,"position":4},"title":"Getting the Battery Level on Android With Delphi","date":"01 Oct 2013","format":false,"excerpt":"Over the past few days I posted a two part series showing how to obtain the current battery level as part of the implementation of an Android AppWidget using Oxygene. As far as I can tell AppWidgets simply aren't possible using Delphi but reading the battery is quite straightforward Android\u2026","rel":"","context":"In &quot;Android&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":1199,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/1199\/","url_meta":{"origin":2416,"position":5},"title":"Oxygene &#8220;Nougat&#8221; is Mac and iOS !","date":"06 Sep 2012","format":false,"excerpt":"Marc Hoffman has confirmed that \"Nougat\" is to Mac\/iOS as \"Cooper\" was to Java. \u00a0Some have speculated that this will be based on Mono, but Oxygene has had Mono covered for some time already, so I strongly doubt that this is the case. Far more likely is that just as\u2026","rel":"","context":"In &quot;Delphi&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/posts\/2416"}],"collection":[{"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/comments?post=2416"}],"version-history":[{"count":12,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/posts\/2416\/revisions"}],"predecessor-version":[{"id":2429,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/posts\/2416\/revisions\/2429"}],"wp:attachment":[{"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/media?parent=2416"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/categories?post=2416"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/tags?post=2416"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}