Creating Lists and printing them
The complete source of collectionTypes_list_creation.ek9, compiled by the EK9 compiler. Shown on collectionTypes.html.
#!ek9 defines module site.collectionTypes.listCreation defines function toString as pure -> item as Integer <- rtn as String: $item isSet as pure -> item as Integer <- rtn as Boolean: item? defines program ListCreationExample() stdout <- Stdout() //A couple of ways to create and empty List of Integer aList as List of Integer: List() of Integer bList <- List() of Integer //But if you have a value you want to use from the outset then use this mechanism //The compiler can infer the type is a List of Integer from this. cList <- List(1) stdout.println(`${aList} ${bList} ${cList}`) //If you have a full set of integers you know from the outset then you can use //[...] as a short hand for Lists (but they are not arrays and cannot be indexed with []). l1 as List of Integer: [ 57, 55, 26, 24, 21 ] //This inferred declaration is preferred and more succinct l2 <- [ 1, 2, 3, 4, 5, 6, 7, Integer() ] //List has a $ operator (i.e. convert to string) and so can just print the contents out. stdout.println("List l1 is " + $l1) //You can use interpolated Strings if you wish. stdout.println(`List l2 is ${l2}`) //Clearly if you had many items, the line length would get very long, //so you can declare lists like this. Also very useful if the items in the list have //complex constructors. l3 <- [ 1, 2, 3, 4, 5, 6, 7, Integer() ] //Again you can just print out like this stdout.println("List l3 is " + $l3) //But the alternative is to use streaming pipelines cat l3 | filter by isSet | map with toString > stdout
Download collectionTypes_list_creation.ek9
Output
[] [] [1] List l1 is [57, 55, 26, 24, 21] List l2 is [1, 2, 3, 4, 5, 6, 7, unset] List l3 is [1, 2, 3, 4, 5, 6, 7, unset] 1 2 3 4 5 6 7