How to build OpenJDK 9 on macOS Sierra

Continuing with my research into Programming Languages (and Compilers in particular), I started looking through the (considerably abstruse) documentation on the OpenJDK site. My patience paid off in the end and I ended up getting a lot of useful information on what I was looking for in particular – the javac source code and documentation. One of my earmarked projects for this year is to modify javac to allow some for extra syntax, and since this involves adding additional semantics, I was keen to download and build OpenJDK for myself.

The steps are surprisingly very well documented and easy to follow. To give a personal perspective on the build process (including a gotcha regarding JDK9), here is the list of steps to download OpenJDK 9 and build the whole system from scratch (for experimentation/contributing to OpenJDK, what have you). Note that the latter steps are specifically for macOS. However, most of the steps are more or less the same across platforms):

  1. First, install Mercurial if you already don’t have it. This was a bit irksome for me at first (being primarily a Git user). If you have Homebrew installed, then it is as trivial as:
    $ brew install hg

    Then, ensure that you have the following settings in your ~/.hgrc file. In case you don’t have a .hgrc file, create one like so:
    $ touch ~/.hgrc

    Add the following lines to the ~/.hgrc file:

    [settings]
    fetch = 
    mq = 
    
  2. Now, clone the OpenJDK 9 repository (for some reason, hg tclone did not work for me (as specified in the documentation), but the following did steps worked just fine:
     $ hg clone http://hg.openjdk.java.net/jdk9/dev 9dev
     $ cd 9dev
     $ sh ./get_source.sh
     

    The last step will retrieve all the necessary code and build environment into your local repository, so this does take some time.

  3. Now, one caveat here – to build OpenJDK, you need an existing JDK installation (the documentation mentions that any standard variant will do). This is called the “boot JDK”. However, I found that the build does not go through with JDK 9 (from the error messages, it looks like Reflection due to the new modules system is the main culprit). In that case, you can use an older version (say, JDK 8) to perform the build instead.

    In the case of macOS, you can use the following command to find the available JDKs on your machine:

     Macushla:RacketMacros z0ltan$ /usr/libexec/java_home -V
     Matching Java Virtual Machines (2):
      9, x86_64:	"Java SE 9-ea"	/Library/Java/JavaVirtualMachines/jdk-
      9.jdk/Contents/Home
      1.8.0_112, x86_64:	"Java SE 8"	
      /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home
    
      /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
     

    The last line shows the current default JDK. Before proceeding with the build, you can either change the default version, or you can simply pass in a different “boot JDK” to the configuration step (preferable).

    Now, let’s generate the configuration file:

    bash configure --with-boot-jdk /Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home/ --disable-warnings-as-errors
    

    Note that I pass in two flags to bash configure : --with-boot-jdk specifying the JDK that I want to use to build OpenJDK, and --disable-warnings-as-errors (this is required on macOS).

    If this command runs successfully, the build is almost certainly going to succeed.

  4. Finally, trigger the build (this should take a bit of time again):
    $ make images
    

    This will dump the generated OpenJDK images into the build directory.

  5. You can test that the generated image is valid:
    Macushla:9dev z0ltan$ ./build/macosx-x86_64-normal-server-release/jdk/bin/java -version
    openjdk version "9-internal"
    OpenJDK Runtime Environment (build 9-internal+0-adhoc.z0ltan.9dev)
    OpenJDK 64-Bit Server VM (build 9-internal+0-adhoc.z0ltan.9dev, mixed mode)
    

    And there you go. All done in under half an hour!

Note that there is a plethora of build options and flags (including cross-compilation capabilities), and you should definitely check out the two HTML pages in the following location of your repository – ./common/doc/building.html, and ./common/doc/testing.html.

Now the real work begins! 😀

How to build OpenJDK 9 on macOS Sierra

Mutual Recursion demo in Rust and Racket (inspired by Haskell)

This is a quick post on a Rust version of the Haskell evens and odds program demonstrating mutual recursion (as shown in Hutton’s book).

First off, the Haskell code:

  evens :: [a] -> [a]
  evens [] = []
  evens (x:xs) = x : odds xs

  odds :: [a] -> [a]
  odds [] = []
  odds (_:xs) = evens xs

A sample run:

*Main> let string = "abcde"
*Main> evens string
"ace"
*Main> odds string
"bd"
*Main> string
"abcde"

So the whole ideas is to have the evens functions display all the characters in even positions (starting from 0), and then odds function likewise display all the characters in odd positions.

The evens function acts as the actual accumulator whilst odds is only used as a trampoline for continuing the recursion.

Now, for a rough Rust version of it (preserving the original character array):


fn main() {
    fn evens<T: Copy>(xs: &[T]) -> Vec<T> {
        if xs.is_empty() {
            Vec::new()
        } else {
            cons(&xs[0], &odds(&xs[1..]))
        }
    }

    fn odds<T: Copy>(xs: &[T]) -> Vec<T> {
        if xs.is_empty() {
            Vec::new()
        } else {
            evens(&xs[1..])
        }
    }

    fn cons<T: Copy>(x: &T, xs: &[T]) -> Vec<T> {
        let mut vec = Vec::new();

        vec.push(*x);

        for e in xs.iter() {
            vec.push(*e);
        }
        vec
    }

    let string = String::from("abcde");

    println!("{}",
             String::from_utf8(evens(&string.clone().into_bytes())).unwrap());
    println!("{}",
             String::from_utf8(odds(&string.clone().into_bytes())).unwrap());

    println!("{}", string);
}

And a quick run:

Macushla:EvensAndOdds z0ltan$ rustc evens_and_odds.rs
Macushla:EvensAndOdds z0ltan$ ./evens_and_odds
ace
bd
abcde

So, as can be clearly seen, the original string is left unmodified. Of course this version looks quite dirty, but the nice bit is that &[T] accepts parameters of type Vec (or reference variants) and vice-versa. This enables using slicing extensively and naturally inside the functions. The vector copying code could, of course, be made to work with an API call, but I feel this is much better in its explicit form.

The Racket version looks much nicer, being more amenable to functional constructs than Rust:

#lang racket

(define (evens xs)
  (if (null? xs)
      '()
      (cons (car xs) (odds (cdr xs)))))

(define (odds xs)
  (if (null? xs)
      '()
      (evens (cdr xs))))

(define (main)
  (let ([string "abcde"])
    (displayln (list->string (evens (string->list string))))
    (displayln (list->string (odds (string->list string))))
    (displayln string)))

And a final run for the Racket version:

evens-and-odds.rkt> (main)
ace
bd
abcde
Mutual Recursion demo in Rust and Racket (inspired by Haskell)

A bit of play with Rust macros

Here are a couple of macros that I wrote up on a slow evening. The first one provides a nice literal way of creating maps, and the second one mimicks Haskell’s list comprehension syntax in a rather crude manner.

My aim originally had been to:

  • have a simple if-then-else structure created in Rust, something like so:
    fn main() {
      let res = if 2 > 3 then "Yes" else "No";
    }
    

    However, this did not appear to be possible with the current macro support in Rust since a fragment of type expr (expression) can be followed only by the following sigils –=> ; ,. So much for that.

  • and secondly, to be able to replicate Haskell’s list comprehension syntax in its entirety, allowing for any possible generator. However, I then realised that Rust’s macro system also did not support actual evaluation of code during expansion like Common Lisp or Scheme/Racket does, even though it does work on the actual AST and not merely text. So out that went through the window as well.

So here’s the first macro demo:

use std::collections::HashMap;

macro_rules! my_map {
    ($($key: expr => $val: expr)*) => {
        {
            let mut map = HashMap::new();

            $(
                map.insert($key, $val);
            )*

          map
        }
    };
}

fn main() {
    let my_map = my_map!{
        1 => "One"
        2 => "Two"
        3 => "Three"
        4 => "Four"
        5 => "Five"
    };

    println!("{:?}", my_map);
}

Nothing fancy here, but you must say that it does look nicer, almost Ruby-esque! Here’s the code run:

Macushla:List_Comprehension_Macro z0ltan$ ./map
{2: "Two", 1: "One", 3: "Three", 5: "Five", 4: "Four"}

And here’s the poor man’s list comprehension that is not only limited in scope, but also entirely inflexible in its syntax (I just couldn’t be bothered tinkering with it for little return):

macro_rules! compr {
    ($id1: ident | $id2: ident <- [$start: expr ; $end: expr] , $cond: expr) => {
        {
            let mut vec = Vec::new();

            for num in $start..$end + 1 {
                if $cond(num) {
                    vec.push(num);
                }
            }

            vec
        }  
    };
}

fn even(x: i32) -> bool {
    x%2 == 0
}

fn odd(x: i32) -> bool {
    x%2 != 0
}

fn main() {
    let evens = compr![x | x <- [1;10], even];
    println!("{:?}", evens);

    let odds = compr![y | y <- [1;10], odd];
    println!("{:?}", odds);
}

As you can see, the ident fragments are completely for show, I cannot use .. in the generator (again due to restrictions on what can follow a expr fragment), and the guards don’t even check against the supposed identifier that’s supposed to be collecting the results into the final list/vector! Anyway, here’s the code run output:

Macushla:List_Comprehension_Macro z0ltan$ rustc list_compr.rs
Macushla:List_Comprehension_Macro z0ltan$ ./list_compr
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

Not too shabby, eh? In all seriousness though, while Rust’s macros are a big improvement over the debacle that is C’s macro system, the surface similarities to Racket’s powerful macro system ends right there – on the surface. As it stands now, there are far too many restrictions on the macro system for it to be considered a viable way of extending the syntax of the language, or even creating new languages (as in the Racket world).

EDIT: The list comprehension macro can actually be improved by using tt for the start and end of the range – this also allows .. to be used much in the Haskell way. Moreover, now we can actually simulate the exact Haskell syntax (for this very specific case, of course), and also make use of the identS as well.

Here’s the new code, but I’m keeping the old code up to remind myself that I can be a doddering idiot at times!

Updated macro:

macro_rules! compr {
    ($id1:ident | $id2:ident <- [$start:tt..$end:tt] , $cond:tt $id3:ident) => {
        {
            let mut vec = Vec::new();
 
            for $id1 in $start..$end + 1 {
                if $cond($id3) {
                    vec.push($id2);
                }
            }
 
            vec
        }  
    };
}
 
fn even(x: i32) -> bool {
    x%2 == 0
}
 
fn odd(x: i32) -> bool {
    x%2 != 0
}
 
fn main() {
    let evens = compr![x | x <- [1..10], even x];
    println!("{:?}", evens);
 
    let odds = compr![y | y <- [1..10], odd y];
    println!("{:?}", odds);
}

And a run just to make sure it’s working:

Macushla:List_Comprehension_Macro z0ltan$ rustc list_compr.rs
Macushla:List_Comprehension_Macro z0ltan$ ./list_compr
[2, 4, 6, 8, 10]
[1, 3, 5, 7, 9]

That’s much better!

A bit of play with Rust macros

The Observer pattern in Rust

Here is a simple implementation of the Observer pattern in Rust. First, the code, and then a small bit of explanation of the implementation itself.

The project structure:

Macushla:rust-observer z0ltan$ tree
.
├── Cargo.lock
├── Cargo.toml
└── src
    ├── lib.rs
    └── main.rs

1 directory, 4 files

The client code:

extern crate rust_observer;

use rust_observer::*;

fn main() {
    let mut foo = EvenCounter::new();
    let (bar, baz, quux) = (Box::new(EvenObserver::new("bar".to_string())),
                            Box::new(EvenObserver::new("baz".to_string())),
                            Box::new(EvenObserver::new("quux".to_string())));

    foo.register(bar);
    foo.register(baz);
    foo.register(quux);

    foo.run();
}

Nothing special here – just creating an Observable object of type EvenCounter, and then three instances of EvenObserver, which implements the Observer type.

The idea is to have the observers get notified whenever the observable object’s counter is an even number (it runs the counter in an infinite loop).

And finally, the actual implementation:

/// the observable type
pub trait Observable<T> {
    fn register(&mut self, observer: Box<Observer<Item = T>>);
}

pub trait Observer {
    type Item;

    fn notify(&self, val: &Self::Item);
}


/// the actual structs which implement the Observable and Observer
/// traits

/// the specific Observable
pub struct EvenCounter {
    counter: u32,
    observers: Vec<Box<Observer<Item = u32>>>,
}

impl EvenCounter {
    pub fn new() -> Self {
        EvenCounter {
            counter: 0u32,
            observers: Vec::new(),
        }
    }

    pub fn run(&mut self) {
        loop {
            use std::thread;
            use std::time::Duration;

            thread::sleep(Duration::from_millis(self.get_rand_duration()));

            self.counter += 1;

            if self.counter % 2 == 0 {
                for observer in self.observers.iter() {
                    observer.notify(&self.counter);
                }
            }
        }
    }

    fn get_rand_duration(&self) -> u64 {
        if cfg!(target_os = "windows") {
            500u64
        } else {
            use std::process::Command;
            use std::str::FromStr;

            let rand_cmd = Command::new("sh")
                .arg("-c")
                .arg("echo $(( $RANDOM%1000 + 1 ))")
                .output()
                .expect("failed to get OS RNG");

            u64::from_str(&String::from_utf8(rand_cmd.stdout).unwrap().trim()).unwrap()
        }
    }
}

impl Observable<u32> for EvenCounter {
    fn register(&mut self, observer: Box<Observer<Item = u32>>) {
        self.observers.push(observer);
    }
}

/// the specific Observer type
pub struct EvenObserver {
    name: String,
}

impl EvenObserver {
    pub fn new(name: String) -> Self {
        EvenObserver { name: name }
    }

    fn name(&self) -> &str {
        &self.name
    }
}

impl Observer for EvenObserver {
    type Item = u32;

    fn notify(&self, val: &Self::Item) {
        println!("{} got {}", self.name(), val);
    }
}

As you can see, the types themselves are implemented as traits, and then the specific concrete types used for the example implement these traits.

The Observable type is quite simple – it is generic over the type that its observers can get notified about. Registration of observers is done through the required method, register. Also note the Box type being used here instead of a real trait object. Sometimes it’s much easier just to box things up than bothering about lifetimes and such.

The Observer type is more interesting. It has a single method, notify which the observable object uses to call the observers. The type of value that is retrieved from the observable object is made an “Associate Type” of the Observer trait. I find this to be a much cleaner approach than defining the trait itself to be parameterized over a generic type.

A simple test run:

Macushla:rust-observer z0ltan$ cargo run
   Compiling rust_observer v0.1.0 (file:///Users/z0ltan/Projects/Playground/DesignPatterns/Observer/Rust/rust-observer)
    Finished dev [unoptimized + debuginfo] target(s) in 0.61 secs
     Running `target/debug/rust_observer`
bar got 2
baz got 2
quux got 2
bar got 4
baz got 4
quux got 4
bar got 6
baz got 6
quux got 6
bar got 8
baz got 8
quux got 8
bar got 10
baz got 10
quux got 10
bar got 12
baz got 12
quux got 12
bar got 14
baz got 14
quux got 14
^C

Very satisfying indeed!

The Observer pattern in Rust

A visitor pattern implementation in Rust

I have recently been studying the ANTLR parser-generator framework, and one of its core approaches is separating the core parsing logic from implementation details. It achieves this using two major patterns – the Listener pattern and the Visitor pattern. This is easily achieved in an Object-oriented language like Java. I was curious to see how that would translate into a language like Rust, hence this post.

Rust, while not quite being an Object-oriented language, does support static and dynamic dispatch. In this case, we are interested in dynamic dispatch, and “Trait Objects” are the main way in which Rust support this feature. However, one problem with using trait objects is that the runtime really doesn’t directly provide us with any way of retrieving the specific type at runtime. This means that calling any struct specific methods on the fly isn’t really that straightforward. The other problem (specific to the Visitor pattern) is that Rust doesn’t have the notion of method overloading. This means that the only sane approach to implementing the pattern in Rust would be to pattern match against the trait object and invoke the appropriate logic, which leads us back to the first point.

A bit of Googling leads us to a practical (if not so elegant) approach of determining the concrete type that implemented the trait at runtime by using std::any::Any. This approach entails providing a method that returns a trait object of type Any for each concrete type that implements the trait, and also explicitly checking the concrete type during pattern matching – there really is no way of extracting the concrete type directly. Instead, we have to try downcasting the trait object to each concrete type and checking if we have a match or not. While this approach works fine for our custom types (the types and count of which we know), this clearly wouldn’t work in a scenario where we are working with third-party types.

In any case, here is the code implementing a simple Visitor pattern where we visit each component of a House type, and perform some custom processing independent of the actual data structures.

Here is the overall layout of the code:

Macushla:rust_visitor z0ltan$ tree
.
├── Cargo.lock
├── Cargo.toml
└── src
    ├── lib.rs
    ├── main.rs
    └── visitors.rs

1 directory, 5 files

Here is the client code, main.rs:

extern crate rust_visitor;

use rust_visitor::*;

fn main() {
    let house = House::new();

    // simply print out the house elements
    house.accept(&visitors::HouseElementListVisitor::new());
   
    println!();
     
    // do something with the elements of a house
    house.accept(&visitors::HouseElementDemolishVisitor::new());
}

So we can see that we create the House element, and then pass in two different implementations of the HouseElementVisitor trait.

Here is the code defining the components of a House:

use std::any::Any;

pub mod visitors;

use visitors::HouseElementVisitor;

/// This represents and element of a house.
/// Each type that implements this trait
/// supports being processed by a visitor.
pub trait HouseElement {
    fn accept(&self, visitor: &HouseElementVisitor);
    fn as_any(&self) -> &Any;
}


/// Define the house entity and its elements

pub struct House {
    components: Vec<Box<HouseElement>>,
}

impl House {
    pub fn new() -> Self {
        House {
            components: vec![Box::new(Livingroom::new()), Box::new(Bedroom::new()), 
                            Box::new(Bathroom::new()), Box::new(Kitchen::new())],
        }
    }
}

impl HouseElement for House {
    fn accept(&self, visitor: &HouseElementVisitor) {
        for component in self.components.iter() {
            component.accept(visitor);
        }

        visitor.visit(self);
    }

    fn as_any(&self) -> &Any { self }
}

struct Livingroom {}

impl Livingroom {
    fn new() -> Self {
        Livingroom{}
    }
}

impl HouseElement for Livingroom {
    fn accept(&self, visitor: &HouseElementVisitor) {
        visitor.visit(self);
    }

    fn as_any(&self) -> &Any { self }
}


struct Bedroom {}

impl Bedroom {
    fn new() -> Self {
        Bedroom {}
    }
}

impl HouseElement for Bedroom {
    fn accept(&self, visitor: &HouseElementVisitor) {
        visitor.visit(self);
    }

    fn as_any(&self) -> &Any { self }
}


struct Bathroom {}

impl Bathroom {
    fn new() -> Self {
        Bathroom {}
    }
}

impl HouseElement for Bathroom {
    fn accept(&self, visitor: &HouseElementVisitor) {
        visitor.visit(self);
    }

    fn as_any(&self) -> &Any { self }
}


pub struct Kitchen {}

impl Kitchen {
    fn new() -> Self {
        Kitchen {}
    }
}

impl HouseElement for Kitchen {
    fn accept(&self, visitor: &HouseElementVisitor) {
        visitor.visit(self);
    }

    fn as_any(&self) -> &Any { self }
}

As can be seen, each implementation of the HouseElement trait defines a method, as_any that returns self as the specific type of the trait object, &Any. This will help the visitor implementation match and find the actual concrete type to do the processing specific to that visitor and that particular HouseElement component.

Finally, here is the actual implementation of the visitors:

//! This module defines the `HouseElementVisitor` trait which defines the capabilities
//! of a type to process the components of a `HouseElement` entity, and also defines
//! a couple of visitor types that do completely different processing.

use ::*;

pub trait HouseElementVisitor {
    fn visit(&self, element: &HouseElement);
}

pub struct HouseElementListVisitor {}

impl HouseElementListVisitor {
    pub fn new() -> Self {
        HouseElementListVisitor {}
    }
}

impl HouseElementVisitor for  HouseElementListVisitor {
    fn visit(&self, element: &HouseElement) {
        if element.as_any()
            .downcast_ref::<House>()
            .is_some() {
            println!("Visiting the House...");
        }

        if element.as_any()
            .downcast_ref::<Livingroom>()
            .is_some() {
            println!("Visiting the Living Room...");
        }

        if element.as_any()
            .downcast_ref::<Bedroom>()
            .is_some() {
            println!("Visiting the bedroom...");
        }

        if element.as_any()
            .downcast_ref::<Kitchen>()
            .is_some() {
                println!("Visiting the kitchen...");
        }
    }
}


pub struct HouseElementDemolishVisitor {}

impl HouseElementDemolishVisitor {
    pub fn new() -> Self {
        HouseElementDemolishVisitor {}
    }
}

impl HouseElementVisitor for HouseElementDemolishVisitor {
    fn visit(&self, element: &HouseElement) {
        if element.as_any()
            .downcast_ref::<House>()
            .is_some() {
            println!("Annihilating the House...!!!");
        }

        if element.as_any()
            .downcast_ref::<Livingroom>()
            .is_some() {
            println!("Bombing the Living Room...!!!");
        }

        if element.as_any()
            .downcast_ref::<Bedroom>()
            .is_some() {
            println!("Decimating the bedroom...!!!");
        }

        if element.as_any()
            .downcast_ref::<Kitchen>()
            .is_some() {
                println!("Destroying the kitchen...!!!");
        }
    }
}

Dirty, but at least it works. The problem, as mentioned before, is that in order to perform specific processing using dynamic dispatch, we use the trait object &HouseElement. However, in order to match against the concrete type, we need to try and match the downcasted reference against each concrete type. This is what the element.as_any().downcast_ref::() code does.

Let’s try it out!

Macushla:rust_visitor z0ltan$ cargo run
   Compiling rust_visitor v0.1.0 (file:///Users/z0ltan/Projects/Blog/Visitor_in_Rust/rust_visitor)
    Finished dev [unoptimized + debuginfo] target(s) in 0.56 secs
     Running `target/debug/rust_visitor`
Visiting the Living Room...
Visiting the bedroom...
Visiting the kitchen...
Visiting the House...

Bombing the Living Room...!!!
Decimating the bedroom...!!!
Destroying the kitchen...!!!
Annihilating the House...!!!

Excellent! Clunky and inelegant, but at least it works.

UPDATE: The implementations of the HouseElementVisitor trait can be simplified into a more elegant match expression block and using the is method of the Any trait as shown below:

Updated HouseElementListVisitor:

impl HouseElementVisitor for  HouseElementListVisitor {
    fn visit(&self, element: &HouseElement) {
        match element.as_any() {
            house if house.is::<House>() => println!("Visiting the house..."),
            living if living.is::<Livingroom>() => println!("Visiting the Living room..."),
            bedroom if bedroom.is::<Bedroom>() => println!("Visiting the bedroom..."),
            kitchen if kitchen.is::<Kitchen>() => println!("Visiting the kitchen..."),
            _ => {}
        }
    }
}

And the HouseElementDemolishVisitor implementation:

impl HouseElementVisitor for HouseElementDemolishVisitor {
    fn visit(&self, element: &HouseElement) {
        match element.as_any() {
            house if house.is::<House>() => println!("Annihilating the house...!!!"),
            living if living.is::<Livingroom>() => println!("Bombing the Living room...!!!"),
            bedroom if bedroom.is::<Bedroom>() => println!("Decimating the bedroom...!!!"),
            kitchen if kitchen.is::<Kitchen>() => println!("Destroying the kitchen...!!!"),
            _ => {}
        }
    }
}

Much more readable in my opinion, and it also hides the somewhat ugly downcast_ref::() bit!

A visitor pattern implementation in Rust

A basic multimap prototype in Rust

Recently, I have been working on a couple of projects, and in one of them, the logic required the use of a multimap. Now, this project is in Rust, and the standard Rust map types, `HashMap` and `BTreeMap` do not support duplicate keys.
Of course, there are full-blown crates available that provide multimap functionality.

However, this being a dead simple project, I decided to roll one out myself. This version simply wraps a `HashMap<K, Vec>` instance inside the custom data structure, but the advantage is that the client API remains consistent and never the wiser about the innards of the actual multimap type. Since I just needed `insert`, `get`, and `iter`, I implemented those for the custom multimap. If needed, the entire API of the `HashMap` type could be implemented for `MHashMap` as well.

Here is the code. It is simple enough that no explanation is really required:

#![allow(dead_code)]

/// A simple wrapper around a HashMap to simulate the basic functionality
/// of a multimap.

use std::collections::HashMap;
use std::hash::Hash;
use std::collections::hash_map::Iter;


#[derive(Debug)]
struct MHashMap<K: Eq + PartialEq + Hash, V>{
    map: HashMap<K, Vec<V>>,
}

impl<K, V> MHashMap<K, V> 
    where K : Eq + PartialEq + Hash
{
    fn new() -> Self {
        MHashMap {
            map: HashMap::new(),
        }
    }

    fn iter(&self) -> Iter<K, Vec<V>> {
        self.map.iter()
        
    }

    fn insert(&mut self, k: K, v: V) {
        if self.map.contains_key(&k) {
                self.map.get_mut(&k).unwrap().push(v);
        } else {
            self.map.insert(k, vec![v]);
        }
    }

    fn get(&self, k: &K) -> Option<&Vec<V>> {
        self.map.get(&k)
    }

    fn get_mut(&mut self, k: &K) -> Option<&mut Vec<V>> {
        self.map.get_mut(&k)
    }
}


fn main() {
    let mut mmap = MHashMap::new();

    mmap.insert(1, "One");
    mmap.insert(1, "Uno");
    mmap.insert(1, "Ein");
    mmap.insert(2, "Two");
    mmap.insert(3, "Three");

    println!("{:?}", mmap);

    let key = 1;

    match mmap.get(&key) {
        Some(vals) => println!("Got {:?} for key {}", vals, key),
        None => println!("Key {} not found!", key),
    }

    for entry in mmap.iter() {
        println!("{} = {:?}", entry.0, entry.1);
    }
}

A small test run:

Macushla:tcp_study z0ltan$ rustc mhash.rs
Macushla:tcp_study z0ltan$ ./mhash
MHashMap { map: {3: ["Three"], 1: ["One", "Uno", "Ein"], 2: ["Two"]} }
Got ["One", "Uno", "Ein"] for key 1
3 = ["Three"]
1 = ["One", "Uno", "Ein"]
2 = ["Two"]

Short and simple!

A basic multimap prototype in Rust

A quick comparison of Euclid’s Algorithm in Haskell, Rust, and D

I recently procured a copy of Graham Hutton’s most excellent book, “Programming in Haskell” (2nd Edition). I had earlier worked through the first edition, and that is the book that really opened my eyes to the power of Haskell! Having become a bit rusty with my Haskell, I decided to work through the second edition book (which is considerably larger and more comprehensive). As part of that exercise, I decided to use a lazy weekend afternoon to code up Euclid’s GCD Algorithm in Haskell, Rust and in D. Just for a quick visual comparison of how the languages look. Here’s how they look:

First off, the Haskell version, which is the best looking one in my opinion:

Macushla:Playground z0ltan$ cat Euclid.hs
module Main where

euclid :: Int -> Int -> Int
euclid m n | m <= 0 && n <= 0 = error "GCD works for positive numbers only"
           | m == n = m
           | m < n = euclid m (n-m)
           | otherwise = euclid (m-n) n

main :: IO ()
main = do putStrLn "Enter the first number: "
          x <- getLine
          putStrLn "Enter the second number: "
          y <- getLine
          let x' = read x :: Int
          let y' = read y :: Int

          putStrLn $ "The GCD of " ++ x
                     ++ " and " ++ y
                     ++ " is " ++ show (euclid x' y')

Macushla:Playground z0ltan$ ghc Euclid.hs
[1 of 1] Compiling Main             ( Euclid.hs, Euclid.o )
Linking Euclid ...
Macushla:Playground z0ltan$ ./Euclid
Enter the first number:
12
Enter the second number:
18
The GCD of 12 and 18 is 6

Here’s the Rust version (a bit uglier, but the Pattern Matching is quite nice):

Macushla:Playground z0ltan$ cat euclid.rs
use std::io;
use std::str::FromStr;
use std::cmp::Ordering;

fn get_number(prompt: &str) -> u32 {
    println!("{}", prompt);

    let mut input = String::new();

    io::stdin().read_line(&mut input)
        .expect("no input!");

    u32::from_str(input.trim()).unwrap()
}

fn main() {
    let x = get_number("Enter the first number: ");
    let y = get_number("Enter the second number: ");

    println!("The GCD of {} and {} is {}", x, y, euclid(x, y));
}

fn euclid(m: u32, n: u32) -> u32 {
    assert!(m > 0 && n > 0);

    match m.cmp(&n) {
        Ordering::Equal => m,
        Ordering::Less => euclid(m, n-m),
        Ordering::Greater => euclid(m-n, n),
        }
}
Macushla:Playground z0ltan$ rustc euclid.rs && ./euclid
Enter the first number:
12
Enter the second number:
18
The GCD of 12 and 18 is 6

And finally, here is the D version – clean, succinct, and a pleasure to read as always:

Macushla:Playground z0ltan$ cat euclid.d
import std.stdio: readln, writeln, writefln;

uint get_number(string prompt) {
    writeln(prompt);

    import std.conv: to;
    import std.string: chomp;

    return readln().chomp().to!(uint);
}

void main() {
    uint x = get_number("Enter the first number: ");
    uint y = get_number("Enter the second number: ");

    writefln("The GCD of %s and %s is %s", x, y, euclid(x, y));
}

uint euclid(uint m, uint n) {
    assert(m > 0 && n > 0);

    if (m < n) {
        return euclid(m, n-m);
    } else if (m == n) {
        return m;
    } else {
        return euclid(m-n, n);
    }
}
Macushla:Playground z0ltan$ dmd -run euclid.d
Enter the first number:
12
Enter the second number:
18
The GCD of 12 and 18 is 6

One thing is for sure. Aside from syntactic differences, most modern languages are all converging in terms of paradigms and features. Hell, even keeping languages like Haskell and Idris aside, most mainstream languages are also converging on the syntactical front! Anyway, this was a fun little exercise on a slow afternoon. I personally like the Haskell version best , followed by the D version, and then finally the Rust version (ruined by the somewhat ugly I/O syntax). What do you think?

A quick comparison of Euclid’s Algorithm in Haskell, Rust, and D

Guessing Game in Kotlin

This is just a quick post showing the canonical implementation of the Guessing Game in Kotlin. While Kotlin may not have the full-blown Pattern-matching abilities of Rust, it has a pretty powerful switching mechanism (more powerful than that available in D). Here is how the code looks, and a sample run follows thereafter:

import java.util.Random

fun main(args: Array<String>) {
    val secretNumber = Random().nextInt(100)

    println("Welcome to the Guessing Game!\n")

    var guess: Int
    var attempts=0

    while (true) {
        print("Enter your guess (1-100): ")
        guess = readLine()!!.toInt()

        when (guess.compareTo(secretNumber)) {
                -1 -> { println("Too small!"); attempts++ }
                 0 -> { attempts++; println("You win! You took $attempts guesses!"); return }
                 1 -> { println("Too big!"); attempts++ }
        }
    }
}

Short and elegant, and the availability of free-functions (at least from the user’s perspective) is a great feature! Here’s a test run:

Macushla:Learn Kotlin z0ltan$ kotlinc GuessingGame.kt -include-runtime -d GuessingGame.jar
Macushla:Learn Kotlin z0ltan$ java -jar GuessingGame.jar
Welcome to the Guessing Game!

Enter your guess (1-100): 50
Too big!
Enter your guess (1-100): 25
Too small!
Enter your guess (1-100): 38
Too big!
Enter your guess (1-100): 31
You win! You took 4 guesses!
Guessing Game in Kotlin

Demoing a simple module in Java 9

In the spirit of the upcoming Java 9 release, I decided to port my D version of the “Guessing game” into Java, but with a twist. I thought that it would be a nice touch to develop the game into a nice module, and turn the process of developing it into an approachable starter tutorial for creating, using, and most importantly, understanding the basics of Java 9 modules.

Background

One of the biggest changes in Java 9 is the introduction of support for modules into the language itself. The rationale and reasoning behind it is very well documented on the OpenJDK site under JEP261.

However, if you find that heavy reading, a wonderfully succinct and clear Quick Start
is also provided for developers who want to simply get on with it. This post is based on that tutorial.

Before we get started with the actual game, I just wanted to ruminate a bit on why I think it’s a welcome idea that modules are being introduced into the language itself. A lot of people conflate packages in Java with modularity. Well, in a sense that does make sense. However, I like to view it as more of a namespacing mechanism than anything else.

Modularity, by definition, would imply a stronger separation of concerns – classes and interfaces wrapped in packages wrapped within modules. Java 9 modules achieve precisely that – they control which packages (and thereby which classes) are visible outside the module itself. Whereas previously we could just toss any old JAR file into the classpath and load classes at will, now we can only do so if the module they reside in explicitly expose them. Very nice!

The game

The game is dead simple – the program generates a secret number in the range [1, 100], and it’s the player’s job to guess the number.

The setup

Okay, so let’s start off by creating a directory for our game module.

Macushla:modules z0ltan$ mkdir guessing-game
Macushla:modules z0ltan$ cd guessing-game

Now, let’s create a directory called mods where we will store the generated module, and also a directory called src (following convention, not strictly enforced) which will hold the module source code:

Macushla:guessing-game z0ltan$ mkdir mods
Macushla:guessing-game z0ltan$ mkdir src
Macushla:guessing-game z0ltan$ tree .
.
├── mods
└── src

2 directories, 0 files

The naming convention for modules is identical to that of packages (com.foo.bar), so pay close attention to the next few steps. Inside the src directory, let us create a directory named com.guessing (note: it is a single directory, not nested
directories). Also, inside the com.guessing directory, let us create a file called module-info.java:

Macushla:guessing-game z0ltan$ mkdir src/com.guessing
Macushla:guessing-game z0ltan$ touch src/com.guessing/module-info.java
Macushla:guessing-game z0ltan$ tree .
.
├── mods
└── src
    └── com.guessing
        └── module-info.java

3 directories, 1 file

So here’s how it works – the directory com.guessing represents the module that we are creating for the game, and it is signified by the module declaration that we will store inside module-info.java. The casing and hyphenation might throw you off a bit, but that’s how Java knows that you have declared a module, so make sure to get the name right!

Right, so let’s go on ahead and write up the module declaration inside module-info.java. Open up the file in your favourite text editor, and then enter the following metadata inside it:

 module com.guessing {
    exports com.my.guessing.game;
 }

Let’s take a moment to understand this bit – the module keyword is how you introduce a module declaration. So we’re declaring here that com.guessing is a module, and that we are exposing the package structure, com.my.guessing.game
from this module. What does this mean? Well, it means that any other module that wishes to use our module can only access the classes that are in this package structure. This is how modules implement real modularity where only the code that needs to be visible to the outside world is made so.

Since we have declared that we are exposing the package com.my.guessing.game, it follows that we should have that package structure in our src directory as well. Let’s go ahead and
create it:

Macushla:guessing-game z0ltan$ mkdir -p src/com.guessing/com/my/guessing/game

And let’s create out single source file named TheGame.java inside the same location:

Macushla:guessing-game z0ltan$ touch src/com.guessing/com/my/guessing/game/TheGame.java

So here’s how the project tree looks at this stage:

Macushla:guessing-game z0ltan$ tree .
.
├── mods
└── src
    └── com.guessing
        ├── com
        │   └── my
        │       └── guessing
        │           └── game
        │               └── TheGame.java
        └── module-info.java
        

Excellent! So, let’s fill out the code for the game now, inside TheGame.java

package com.my.guessing.game;

import java.util.Random;
import java.util.Scanner;

public class TheGame {
	private static Random rand;

	public TheGame() {
		rand = new Random();
	}

	public static void main(String[] args) {
		TheGame game = new TheGame();
	
		game.play();
	}

	private void play() {
		try{
			Scanner in = new Scanner(System.in);		

			System.out.println("Welcome to the Guessing Game!");

			// secret number in the range [1, 100]
			int mySecretNumber = rand.nextInt(100) + 1;
			int attempts = 0;

			while (true) {
				attempts++;

				System.out.println("Enter your guess (between 1 and 100 inclusive)");
				int guess = in.nextInt();

				if (guess < mySecretNumber) {
					System.out.println("Too small!");
				} else if (guess == mySecretNumber) {
					System.out.format("You win! You took %d guesses!\n", attempts);
				} else {
					System.out.println("Too big!");
				}
			}
		} catch (Exception ex) {
			System.err.println("Oh no! Something went terribly wrong. Aborting game!");
			System.exit(1);
		}
	}
}

Nice! So now all we have left to do is to compile the game and run it. Ah, but there remains one more step before we can actually do that. Remember the mods directory we had created in the first step? That directory is meant to hold all the modules that we would generate for our project (there can be as many modules as you like in your project, with various modules dependent on various other modules). In our game, we have only one module,
com.guessing. To hold the contents of this module, we need to create the corresponding module directory in the mods directory, like so:

Macushla:guessing-game z0ltan$ mkdir mods/com.guessing
Macushla:guessing-game z0ltan$ tree .
.
├── mods
│   └── com.guessing
└── src
    └── com.guessing
        ├── com
        │   └── my
        │       └── guessing
        │           └── game
        │               └── TheGame.java
        └── module-info.java

8 directories, 2 files

Excellent! Let’s go ahead and compile the game:

Macushla:guessing-game z0ltan$ javac --module-path=mods -d mods/com.guessing \
  src/com.guessing/module-info.java src/com.guessing/com/my/guessing/game/TheGame.java 
Macushla:guessing-game z0ltan$ tree .
.
├── mods
│   └── com.guessing
│       ├── com
│       │   └── my
│       │       └── guessing
│       │           └── game
│       │               └── TheGame.class
│       └── module-info.class
└── src
    └── com.guessing
        ├── com
        │   └── my
        │       └── guessing
        │           └── game
        │               └── TheGame.java
        └── module-info.java

12 directories, 4 files

Okay, the compilation command requires a bit of explanation – the --module-path option is used to indicate the root directory (or directories) where the module (or modules) is to be stored. In our case, that is the mods directory. The -d flag indicates where the generated class files are to be stored. In our case, this is the mods/com.guessing
directory. Finally, we link in all the source files that need to be compiled, and this includes the module-info.java metadata file as well. Note that all this should be automatically done once IDE support is widely available for Java 9 (IntelliJ apparently has some support for Java 9 already,
and Eclipse also has an extra plugin that supports Java 9).

Also observe the contents of the mods directory. It’s an exact replica of the src directory albeit containing the generated classes.

As a final step, let’s run the game! This is how you would run it from the command-line:

Macushla:guessing-game z0ltan$ java --module-path mods -m com.guessing/com.my.guessing.game.TheGame
Welcome to the Guessing Game!
Enter your guess (between 1 and 100 inclusive)
50
Too small!
Enter your guess (between 1 and 100 inclusive)
75
Too big!
Enter your guess (between 1 and 100 inclusive)
63
Too big!
Enter your guess (between 1 and 100 inclusive)
56
You win! You took 4 guesses!

Again, a bit of commentary on the run command – we again use the --module-path option to tell Java where our module resides, and then we pass the actual fully-qualified name of the class to the -m flag, which tells Java which module we are interested in running. Note that there are various short forms (for instance, we can use
-p> instead of --module-path in this case, refer to the documentation for all the flags and options).

And we’re done!

Extras

One additional interesting feature in Java 9 is that we can bundle our game into a nice little app. To do that, we need to understand that Java 9 actually comes with all its functionality divided into modules. For instance, all core functionality resides in the java.base module. Also note that this module is automatically assumed to be used by all custom modules. For instance, the module declaration that we used for this game could very well have been written explicitly as:

module com.guessing {
   requires java.base;
   exports com.guessing.my.game;
}

where the requires module is the opposite of exports. Beware though that having the requires declaration is not enough to be able to use classes from that module. It only makes the exported packages in that module visible in the require-ing module. That means that in our code, we should still have explicit importS for those public packages. For instance, if we want to find out which modules are present
by default, we can view them so:

Macushla:guessing-game z0ltan$ java --list-modules
java.activation@9-ea
java.annotations.common@9-ea
java.base@9-ea
java.compact1@9-ea
java.compact2@9-ea
java.compact3@9-ea
java.compiler@9-ea
java.corba@9-ea
java.datatransfer@9-ea
java.desktop@9-ea
java.httpclient@9-ea
java.instrument@9-ea
java.jnlp@9-ea
java.logging@9-ea
java.management@9-ea
java.naming@9-ea
java.prefs@9-ea
java.rmi@9-ea
java.scripting@9-ea
java.se@9-ea
java.se.ee@9-ea
java.security.jgss@9-ea
java.security.sasl@9-ea
java.smartcardio@9-ea
java.sql@9-ea
java.sql.rowset@9-ea
... (content elided due to space contraints)

All the modules reside in the $JAVA_HOME/jmods directory, but you might be surprised if you check the contents – they won’t correspond to the output we saw above. The reason for this is the modules that come bundled with the JDK are in “jmod” form, which is a compiled format. The jmod tool comes bundled with the JDK, and can be used to create a jmod binary for our custom modules as well. The terminology for the module format that we have used here is “exploded module”. This JEP contains all the gruesomely interesting details.

Right, so where are we going with this? Ah yes, we wanted to bundle our game into a custom app. Let’s do that (but all this jmod discussion will come in handy later on)!

First off, let’s set our JAVA_HOME environment variable for convenience. Note, this section describes how to set it for macOS users only. For windows users, consult your documentation!

On macOS, one problem is that finding the paths of various installed tools can be a real PITA. Thankfully, we have a bundled tool called java_home to help us out:

Macushla:guessing-game z0ltan$ /usr/libexec/java_home -V
Matching Java Virtual Machines (3):
    9, x86_64:	"Java SE 9-ea"	/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
    1.8.0_112, x86_64:	"Java SE 8"	/Library/Java/JavaVirtualMachines/jdk1.8.0_112.jdk/Contents/Home
    1.8.0_45, x86_64:	"Java SE 8"	/Library/Java/JavaVirtualMachines/jdk1.8.0_45.jdk/Contents/Home

/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home

Okay, so on my machine, I have three different versions of the JDK installed. Clearly, I need to use the Java 9 version, so let’s set the environment variable to use that:

Macushla:guessing-game z0ltan$ export JAVA_HOME="$(/usr/libexec/java_home -v 9)"
Macushla:guessing-game z0ltan$ echo $JAVA_HOME
/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home

Excellent. Now, let’s go ahead and create our app. For this, we use another new tool that comes bundled with the JDK – jlink. As the name suggests, it is a linker, and we use this linker to link our module into Java, and create a custom version of the JVM that contains only our dependencies (in addition to the mandatory java.base module):

Macushla:guessing-game z0ltan$ jlink --module-path $JAVA_HOME/jmods:mlib --add-modules mods/com.guessing \
> --output my_guessing_app
Error: Module com.guessing not found

Module not found? How is it possible? We specified the fully-qualified module name, mods/com.guessing, didn’t we? Well, the reason jlink failed is that it accepts modules in only two formats – either JMOD (as discussed above), or as a JAR file containing our “exploded” module. So before we can bundle our app, there remains just one more step – bundling our app as a JAR or as JMOD. Let’s go for the jAR file
option:


Macushla:guessing-game z0ltan$ jar --create --file=guessing_game@0.0.1.jar \
  --module-version=0.0.1 --main-class=com.my.guessing.game.TheGame -C mods/com.guessing .

Note how we have to specify the module version explicitly. Java 9 modules do not (as yet) support automatic versioning, nor is versioning checked or enforced (as far as I can tell).

And now we can check that the JAR file contains a valid module by passing the --print-module-descriptor
flag to the jar command:

Macushla:guessing-game z0ltan$ jar --print-module-descriptor guessing_game\@0.0.1.jar 
^CMacushla:guessing-game z0ltan$ jar --print-module-descriptor --file guessing_game\@0.0.1.jar 

com.guessing@0.0.1
  requires mandated java.base
  exports com.my.guessing.game
  main-class com.my.guessing.game.TheGame

So it looks like all is in order. Let’s try creating the app now!

Macushla:guessing-game z0ltan$ jlink --module-path $JAVA_HOME/jmods:mlib --add-modules mods/com.guessing/ \
> --output my_guessing_game
Error: Module mods/com.guessing/ not found
Macushla:guessing-game z0ltan$ jlink --module-path $JAVA_HOME/jmods:mlib --add-modules com.guessing/ \
   --output my_guessing_game
Error: Module com.guessing/ not found

What gives? Note that the official convention is to create a directory to contain the JAR or JMOD file, called mlib. The modules that come bundled with the JDK all follow the same convention as well.

So let’s create a directory called mlib in our project root directory:

Macushla:guessing-game z0ltan$ jar --create --file=mlib/guessing_game@0.0.1.jar \
  --module-version=0.0.1 --main-class=com.my.guessing.game.TheGame \
   -C mods/com.guessing .

So the final directory structure looks like so:

Macushla:guessing-game z0ltan$ tree .
.
├── mlib
│   └── guessing_game@0.0.1.jar
├── mods
│   └── com.guessing
│       ├── com
│       │   └── my
│       │       └── guessing
│       │           └── game
│       │               └── TheGame.class
│       └── module-info.class
└── src
    └── com.guessing
        ├── com
        │   └── my
        │       └── guessing
        │           └── game
        │               └── TheGame.java
        └── module-info.java

13 directories, 5 files

The final step is to run the same command that we had tried before:

Macushla:guessing-game z0ltan$ jlink --module-path $JAVA_HOME/jmods:mlib --add-modules com.guessing --output my_guessing_game
Macushla:guessing-game z0ltan$ ls
mlib             mods             my_guessing_game src

Excellent! So we have a directory called my_guessing_game created. Let’s check its
contents:

Macushla:guessing-game z0ltan$ tree my_guessing_game/
my_guessing_game/
├── bin
│   ├── com.guessing
│   ├── java
│   └── keytool
├── conf
│   ├── net.properties
│   └── security
│       ├── java.policy
│       ├── java.security
│       └── policy
│           ├── README.txt
│           ├── limited
│           │   ├── default_US_export.policy
│           │   ├── default_local.policy
│           │   └── exempt_local.policy
│           └── unlimited
│               ├── default_US_export.policy
│               └── default_local.policy
├── lib
│   ├── jli
│   │   └── libjli.dylib
│   ├── jspawnhelper
│   ├── jvm.cfg
│   ├── libjava.dylib
│   ├── libjimage.dylib
│   ├── libjsig.dylib
│   ├── libnet.dylib
│   ├── libnio.dylib
│   ├── libosxsecurity.dylib
│   ├── libverify.dylib
│   ├── libzip.dylib
│   ├── modules
│   ├── security
│   │   ├── blacklist
│   │   ├── blacklisted.certs
│   │   ├── cacerts
│   │   ├── default.policy
│   │   └── trusted.libraries
│   ├── server
│   │   ├── Xusage.txt
│   │   ├── libjsig.dylib
│   │   └── libjvm.dylib
│   └── tzdb.dat
└── release

10 directories, 34 files

Whoa! That’s a lot of files and directories. The good part is that it is now a full-fledged, self-contained Java app containing our game!

Let’s take it for a spin!

Macushla:guessing-game z0ltan$ cd my_guessing_game/
Macushla:my_guessing_game z0ltan$ ls
bin     conf    lib     release
Macushla:my_guessing_game z0ltan$ bin/
com.guessing  java          keytool       
Macushla:my_guessing_game z0ltan$ bin/com.guessing 
Welcome to the Guessing Game!
Enter your guess (between 1 and 100 inclusive)
50
Too big!
Enter your guess (between 1 and 100 inclusive)
25
Too small!
Enter your guess (between 1 and 100 inclusive)
38
Too small!
Enter your guess (between 1 and 100 inclusive)
44
Too small!
Enter your guess (between 1 and 100 inclusive)
47
Too big!
Enter your guess (between 1 and 100 inclusive)
46
Too big!
Enter your guess (between 1 and 100 inclusive)
45
You win! You took 7 guesses!

Noiiiice! However, before you get too excited, note that this is not AOT (Ahead of time compilation)! bin/com.guessing is simply a script file that uses the bundled JVM instance to run the app. We can verify this by checking the contents of com.guessing:

Macushla:bin z0ltan$ cat com.guessing 
#!/bin/sh
JLINK_VM_OPTIONS=
DIR=`dirname $0`
$DIR/java $JLINK_VM_OPTIONS -m com.guessing/com.my.guessing.game.TheGame $@

Still, pretty nice, innit? We have come a long way from your grandfather’s Java, my friends.

One last interesting observation before we collapse from mental overload! Recall the command we had used to check the modules bundled in the default JDK, java --list-modules? Well, let’s try out the same command on the bundled JVM instance in the bin
directory of our app:

Macushla:my_guessing_game z0ltan$ bin/java --list-modules
com.guessing@0.0.1
java.base@9-ea

Heh! As we expected, since our project depends only on two modules, com.guessing, which is our game, and on the mandatory module, java.base, we see that this stripped down JVM only has these two modules, which leads to a very small overall app size as well (if we had dependencies on other modules, then those would be transitively included
as well):

 Macushla:my_guessing_game z0ltan$ cd ..
Macushla:guessing-game z0ltan$ ls
mlib             mods             my_guessing_game src
Macushla:guessing-game z0ltan$ du -m my_guessing_game/
1	my_guessing_game//bin
1	my_guessing_game//conf/security/policy/limited
1	my_guessing_game//conf/security/policy/unlimited
1	my_guessing_game//conf/security/policy
1	my_guessing_game//conf/security
1	my_guessing_game//conf
1	my_guessing_game//lib/jli
1	my_guessing_game//lib/security
13	my_guessing_game//lib/server
31	my_guessing_game//lib
31	my_guessing_game/
Macushla:guessing-game z0ltan$

A mere 31MB with our bundled JVM! Ain’t that nice? Time for a nice beer now!

Demoing a simple module in Java 9

A simple guessing game in D

This short post is inspired by the recent spate of languages introducing themselves through a small game program. As such, here is a version of the guessing game in D.

The objective of the game is very simple – there is a secret number randomly generated per game (in the range [1, 100] for simplicity), and the user has to guess the number to exit the game.

I also wanted to get a bit more practice with the de facto package cum dependency manager for D, dub.

Let’s start off by creating the project:

Macushla:MiniProjects z0ltan$ dub init guessing_game
Package recipe format (sdl/json) [json]: json
Name [guessing_game]: 
Description [A minimal D application.]: A simple guessing game in D
Author name [Timmy Jose]: 
License [proprietary]: MIT
Copyright string [Copyright © 2017, Timmy Jose]: 
Add dependency (leave empty to skip) []: 
Successfully created an empty project in '/Users/z0ltan/Rabota/ProgrammingLanguages/D/MiniProjects/guessing_game'.
Package successfully created in guessing_game

By default, dub also creates a .gitignore file in the root directory of the new project/package.

Here’s how the layout of the default configuration looks like:

Macushla:MiniProjects z0ltan$ cd guessing_game/
Macushla:guessing_game z0ltan$ tree .
.
├── dub.json
└── source
    ├── app.d

1 directory, 2 files

The dub.json file contains the basic configuration metadata for the project, and is for consumption by dub. Its initial contents are the data entered during the creation of the project.

A sample file, app.d is created inside the source directory. These can all be customised, of course.

Okay, so let’s create a new file to contain our guessing game code as a module.

Macushla:MiniProjects z0ltan$ touch source/guessing_game.d

All right, time to code up the game. Here are the contents of source/guessing_game.d

module guessing_game;

import std.stdio;

public void playGame() 
{
	import std.random: uniform;

	immutable uint secretNumber = uniform(1, 101);
	uint guesses = 0;

	writeln("\nLet's play a guessing game. Your task is to guess the secret number (between 1 and 100, inclusive)...");

	import std.conv: ConvException;

	while (true) {
		try {
			uint guess = getNumber("Enter your guess: ");

			++guesses;
			if (guess == secretNumber) {
				writefln("You win! You took %s guesses.", guesses);
				break;
			} else if (guess < secretNumber) {
				writeln("Too small!");
			} else {
				writeln("Too big!");
			}
		} catch (ConvException ex) {
			writeln("Did not get valid input. Try again...");
		}
	}
}


uint getNumber(string prompt) 
{
	writeln(prompt);

	import std.conv: to;
	import std.string: chomp;
		
	return readln().chomp.to!uint;
}

As you can see, this program is trivially readable for anyone who’s worked with C, C++, or indeed Java. The interesting bits to note would be the module system, as well as selective imports of module’s functions inside local lexical scopes.
Thankfully, D comes with a built-in module, std.random in its standard library (Phobos), and we can use the uniform function to generate our random number.

Another interesting bit to note is the following snippet of code:

return readln().chomp.to!uint;

The to! is a template function that is extremely powerful. It can be used to convert almost any type to any other type. In case the conversion fails though, this template function will throw a std.conv.ConvException exception. Note that D does not have checked exceptions (in Java-speak), only unchecked exceptions.

Also note the exception handling mechanism, which is extremely similar to that of Java.

Finally, observe the declaration of playGame as public. The helper function getNumber in source/guessing_game.d, by contrast is private, and not accessible outside the module in which it is defined.

Okay, so this is the guessing game logic. Now let’s take a look at our game’s entry point, source/app.d

import guessing_game;

void main()
{
	guessing_game.playGame();	
}

All we do is import the guessing_game module and then invoke playGame. Note that we could also have written this module like so:

import guessing_game: playGame;

void main() 
{
      playGame();
}     

Let’s try out the game!

Macushla:guessing_game z0ltan$ dub run
Performing "debug" build using dmd for x86_64.
guessing_game ~master: building configuration "application"...
Linking...
Running ./guessing_game 

Let's play a guessing game. Your task is to guess the secret number (between 1 and 100, inclusive)...
Enter your guess: 
50
Too small!
Enter your guess: 
hello
Did not get valid input. Try again...
Enter your guess: 
-1
Did not get valid input. Try again...
Enter your guess: 
75
Too small!
Enter your guess: 
88
Too big!
Enter your guess: 
81
Too big!
Enter your guess: 
78
You win! You took 5 guesses.
A simple guessing game in D