Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014
Upcoming SlideShare
Loading in...5
×
 

Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014

on

  • 174 views

The slide to the Java User Group Talk Exploring Ceylon from Gavin King. ...

The slide to the Java User Group Talk Exploring Ceylon from Gavin King.

Abstrakt:
Ceylon is a new programming language designed for writing large programs in teams. The language emphasizes readability, modularity, typesafety, and tooling. Ceylon programs execute on Java and JavaScript virtual machines. In this session, Gavin King will talk about the ideas behind Ceylon and demonstrate the language, its type system, its module architecture, and its IDE.

Speaker:
Gavin King leads the Ceylon project at Red Hat. He is the creator of Hibernate, a popular object/relational persistence solution for Java, and the Seam Framework, an application framework for enterprise Java. He's contributed to the Java Community Process as JBoss and then Red Hat representative for the EJB and JPA specifications and as lead of the CDI specification.
Now he works full time on Ceylon, polishing the language specification, developing the compiler frontend, and thinking about the SDK and future of the platform. He's still a fan of Java, and of other languages, especially Smalltalk, Python, and ML.

Statistics

Views

Total Views
174
Views on SlideShare
174
Embed Views
0

Actions

Likes
0
Downloads
0
Comments
0

0 Embeds 0

No embeds

Accessibility

Categories

Upload Details

Uploaded via as Adobe PDF

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment

Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014 Exploring Ceylon with Gavin King - JUG BB Talk - Belrin 2014 Presentation Transcript

  • Introducing Ceylon Twelve Ceylon Idioms Gavin King - Red Hat profiles.google.com/gavin.king ceylon-lang.org !
  • ! ! We are fans of Java
  • ! If I appear critical of Java (or any other language) in this presentation it’s because I care about Java and about programming languages and because understanding what’s wrong with something is the first step to improving it
  • ! Powerful, ! Readable, ! Predictable. Verbosity is not the only relevant measure, but it does matter Find more bugs at compile time, thanks to scrupulous use of static typing The developer should be able to reproduce the reasoning of the compiler according to intuitive rules More powerful tools for abstraction, so the static types get in the way less We spend much more time reading other people’s code than we spend writing our own Error messages should be understandable and refer to concepts inside the user’s head
  • ! A Platform, ! Tooling, ! Modularity. Cross platform execution: JVM or JavaScript VM A brand new modular SDK with a minimal language module Static typing enables powerful tools – dynamic languages simply can’t compete The job of tools isn’t to fill in boilerplate, it is to help you understand and evolve the code Ceylon Herd: the community module repository A single unifying module system built into the language, the tooling, the compiler, the runtime
  • “Powerful” • Languages with static typing are less expressive, in a certain narrow sense, than dynamic languages • Ceylon has a very strict type system, fussier even than Java or C# • So to counterbalance that, we need additional power, within the type system, to abstract over things, thus regaining expressivity • Let’s explore the type system via some idioms
  • Idiom #1 Idiom: functions with multiple outcomes For example, an operation might return a Person, an Org, or nothing. ! ! We can handle the different outcomes using instanceof, type casts, and catch: //Java Object findByName(String name) throws NotFoundException { ... } try { Object result = findByName(name); if (result instanceof Org) { Org org = (Org) result; ... } if (result instanceof Person) { Person person = (Person) result; ... } } catch (NotFoundException nfe) { ... }
  • Idiom #1 Idiom: functions with multiple outcomes A function with more than one “outcome” can be defined using a union type. ! ! We can handle the various outcomes using switch: Org|Person|NotFound findByName(String name) => ... ; value result = findByName(name); switch (result) case (is Org|Person) { ... } case (is NotFound) { ... }
  • Idiom #2 Idiom: functions returning null Example: retrieving an element from a map. (Special case of multiple outcomes!) ! ! For a union type of form Null|Item, we have some special syntax sugar. Item? get(Key key) => ... ; value map = HashMap { “CET”->cst, “GMT”->gmt, “PST”->pst }; ! Timezone tz = map[id]; //not well-typed! value offset = map[id].rawOffset; //not well-typed! ! Timezone? tz = map[id]; value offset tz = (map[id] else cet).rawOffset; Item? get(Key key)
  • Idiom #2 Idiom: functions returning null What if we know that get() can’t return null, because of some constraint upon the given key? We can make use of an assertion. ! ! ! A different way to write this code, removing the need for the assertion: ! ! ! A similar idiom shows up in iteration of lists. Item? get(Key key) if (name in map.keys) { //now we know it’s there assert (exists tz = map[name]); return ZonedTime(time, tz); } if (exists tz = map[name]) { return ZonedTime(time, tz); }
  • Idiom #3 Idiom: iteration over lists The following is clumsy: ! ! ! A different way to write this code, removing the need for the assertion: ! ! We never iterate over list indexes in Ceylon. Not even when iterating subranges: Item? get(Key key) for (index in 0:names.size) { assert (exists name = names[index]); print(index + “:” + name); } for (index->name in names.indexed) { print(index + “:” + name); } for (index->name in names[start:length].indexed) { print(index+start + “:” + name); }
  • Idiom #4 Idiom: overloading For example, an operation might apply to an integer, or to a float. ! ! ! Actually two different, unrelated operations. ! //Java float sqrt(float number) { ... } float sqrt(int number) { ... }
  • Idiom #4 Idiom: overloading A function parameter can be defined using a union type. ! ! ! ! Now we have a single operation, and so we can obtain a reference to it: Float sqrt(Float|Integer number) { switch (number) case (is Float) { return number^0.5; } case (is Integer) { return number.float^0.5; } } Float(Float|Integer) sqrtFun = sqrt; ! Float result = sqrtFun(3);
  • Idiom #4 Idiom: overloading In some cases, we must use generics. ! ! ! ! And we can still obtain a reference to it: ! ! Note that the type argument must be supplied (no “rank 2” polymorphism). Num sqr<Num>(Num number) given Num of Float|Integer { switch (number) case (is Float) { ... } case (is Integer) { ... } } Float(Float) sqrFun = sqr<Float>;
  • Idiom #5 Idiom: unions of values Imagine we want to write down the signature of Set.union() in Java: ! ! ! This doesn’t actually compile since Java doesn’t have lower bounded type parameters. (The equivalent thing would work in Scala though.) //Java interface Set<T> { public <U super T> Set<U> union(Set<? extends U> set); } Set<Foo> setOfFoo = ... ; Set<Bar> setOfBar = ... ; ! Set<Object> setOfFoosAndBars = setOfFoo.union(setOfBar);
  • Idiom #5 Idiom: unions of values Unions of values correspond to unions of types! ! ! ! Exactly the right type pops out automatically. interface Set<These> { shared formal Set<These|Those> union<Those>(Set<Those> set); } Set<Foo> setOfFoo = ... ; Set<Bar> setOfBar = ... ; ! Set<Foo|Bar> setOfFoosAndBars = setOfFoo | setOfBar;
  • Idiom #6 Idiom: intersections of values Now let’s consider the case of Set.intersection() in Java. //exercise for the audience I tried a bunch of things and didn’t come close to anything like the right thing.
  • Idiom #6 Idiom: intersections of values Intersections of values correspond to intersections of types! ! ! ! Again, exactly the right type pops out automatically. interface Set<These> { shared formal Set<These&Those> intersection<Those>(Set<Those> set); } Set<Foo> setOfFoo = ... ; Set<Bar> setOfBar = ... ; ! Set<Foo&Bar> setOfFooBars = setOfFoo & setOfBar;
  • Idiom #6 Idiom: intersections of values Example: the coalesce() function eliminates null elements from an Iterable object. ! ! Exactly the right type pops out automatically. ! ! ! (Even though I’m explicitly writing in the types, I could have let them be inferred.) {Element&Object*} coalesce<Element>({Element*} elements) => { for (e in elements) if (exists e) e }; {String?*} words = { “hello”, null, “world” }; {String*} strings = coalesce(words);
  • Idiom #7 Idiom: empty vs nonempty Problem: the max() function can return null, but only when the Iterable object might be empty. ! ! ! What if we know it’s nonempty? A separate function? ! ! ! This doesn’t let us abstract. shared Value? max<Value>({Value*} values) given Value satisfies Comparable<Value> { ... } shared Value maxNonempty<Value>({Value+} values) given Value satisfies Comparable<Value> { ... }
  • Idiom #7 Idiom: empty vs nonempty Solution: the Iterable type has an extra type parameter. ! ! ! Exactly the right type pops out automatically. shared Absent|Value max<Value,Absent>(Iterable<Value,Absent> values) given Value satisfies Comparable<Value> given Absent satisfies Null { ... } Null maxOfNone = max {}; //known to be empty String maxOfSome = max { “hello”, “world” }; //known to be nonempty ! {String*} noneOrSome = ... ; String? max = max(noneOrSome); //might be empty or nonempty
  • Idiom #8 Idiom: multiple return values For example, an operation might return a Name and an Address. ! ! ! ! ! We have to define a class. ! //Java class NameAndAddress { ... } ! NameAndAddress getNameAndAddress(Person person) { return new NameAndAddress(new Name(person.getFirst(), person.getLast()), person.getHome().getAddress()); }
  • Idiom #8 Idiom: multiple return values A function can be defined to return a tuple type. ! ! Now a caller can extract the individual return values: ! ! ! What about other indexes? [Name,Address] getNameAndAddress(Person person) => [Name(person.first, person.last), person.home.address]; value nameAndAddress = getNameAndAddress(person); Name name = nameAndAddress[0]; Address address = nameAndAddress[1]; Null missing = nameAndAddress[3]; Name|Address|Null val = nameAndAddress[index];
  • Idiom #9 Idiom: spreading tuple return values Imagine we want to pass the result of getNameAndAddress() to another function or class initializer. ! ! We can use the spread operator, *, like in Groovy: ! ! Or we can work at the function level, using unflatten() class SnailMail(Name name, Address address) { ... } value snail = SnailMail(*getNameAndAddress(person)); SnailMail(Person) newSnail = compose(unflatten(SnailMail), getNameAndAddress); SnailMail snail = newSnail(person);
  • Idiom #10 Idiom: abstract over function types Example: the compose() function composes functions. ! ! ! But this is not quite as general as it could be! ! ! What about functions with multiple parameters? X compose<X,Y,A>(X(Y) x, Y(A) y)(A a) => x(y(a)); value printSqrt = compose(print,sqrt); value printSum = compose(print,plus<Float>);
  • Idiom #10 Idiom: abstract over function types Solution: abstract over unknown tuple type. ! ! ! ! A little uglier, but does the job! ! ! ! This is actually very useful: write a generic function to memoize another function Callable<X,Args> compose<X,Y,Args>(X(Y) x, Callable<Y,Args> y) given Args satisfies Anything[] => flatten((Args args) => x(unflatten(y)(args))); Anything(Float,Float) printSum = compose(print,plus<Float>);
  • Idiom #11 Idiom: discovery Example: auto-discover classes annotated test. ! We use the Ceylon metamodel: shared test class IdiomTests() { ... } void metamodel() { value declarations = `package org.jboss.example.tests` .annotatedMembers<ClassDeclaration,TestAnnotation>(); for (decl in declarations) { if (decl.parameterDeclarations.empty) { value model = decl.classApply<Anything,[]>(); // instantiate the class print(model()); } } }
  • Idiom #12 Idiom: tree-structured data Tree structures occur everywhere: user interfaces, HTML,“configuration”, etc. In the Java world, we’re forced to use XML for this, losing the advantages of static typing, tools, etc. ! In Ceylon, we can use named arguments: Html html = Html { doctype = html5; Head { title = "Hello"; }; Body { for (name in names) { P("Hello, ``name``!") } }; };