SlideShare una empresa de Scribd logo
1 de 21
Descargar para leer sin conexión
Ten Ceylon Idioms
Gavin King - Red Hat
profiles.google.com/gavin.king	
ceylon-lang.org	

!
“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.
//Java	
!
Object findByName(String name) 	
throws NotFoundException { ... }
!

We can handle the different outcomes using instanceof, type casts, and catch:
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.

!

Org|Person|NotFound findByName(String name) => ... ;

!
We can handle the various outcomes using switch:
value result = findByName(name);	
switch (result)	
case (is Org|Person) { ... }	
case (is NotFound) { ... }
Item? get(Key key)

Idiom #2
Idiom: functions returning null
Example: retrieving an element from a map. (Special case of multiple outcomes!)

!

Item? get(Key key) => ... ;

!
For a union type of form Null|Item, we have some special syntax sugar:
value map = HashMap { “enrique”->cst, “tom”->gmt, “ross”->pst };

Timezone tz = map[name] else cet;
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.

!

if (name in map) {	
assert (exists tz = map[name]);	
!
return ZonedTime(time, tz);	
}

!

A different way to write this code:

!
if (exists tz = map[name]) {	
return ZonedTime(time, tz);	
}
Idiom #3
Idiom: overloading
For example, an operation might apply to an Integer, or to a Float.

!

//Java	
Float sqrt(Float !
number) { ... }	
Float sqrt(Integer number) { ... }

!
Actually two different, unrelated operations.

!
Idiom #3
Idiom: overloading
A function parameter can be defined using a union type.

!
Float sqrt(Float|Integer number) {	
switch (number)	
!
case (is Float) { ... }	
case (is Integer) { ... }	
!
}
!
Now we have a single operation:
Float fourthRoot(Float|Integer number) => sqrt(sqrt(number));
!

And we can obtain a reference to it:
Float(Float|Integer) sqrtFun = sqrt;
Idiom #4
Idiom: multiple return values
For example, an operation might return a Name
//Java	
class NameAndAddress { ... }	

!

and

an Address.

!
!

NameAndAddress getNameAndAddress(Person person) {	
!
return new NameAndAddress(new Name(person.getFirst(), person.getLast()),
person.getHome().getAddress());	
!
}

!
We have to define a class.

!
Idiom #4
Idiom: multiple return values
A function can be defined to return a tuple type.
[Name,Address] getNameAndAddress(Person person) 	
!
=> [Name(person.first, person.last), 	
person.home.address];
!

Now a caller can extract the individual return values:
value nameAndAddress = !
getNameAndAddress(person);	
Name name = nameAndAddress[0];	
!
Address address = nameAndAddress[1];

!
What about other indexes?
Null missing = nameAndAddress[3];	
Name|Address|Null val = nameAndAddress[index];
Idiom #5
Idiom: spreading tuple return values
Imagine we want to pass the result of getNameAndAddress() to another function or
class initializer.

!
class SnailMail(Name name, Address address) { ... }
!
We can use the spread operator, *, like in Groovy:

!

value snail = SnailMail(*getNameAndAddress(person));

!
Or we can work at the function level, using unflatten()
SnailMail(Person) newSnail 	
= compose(unflatten(SnailMail), getNameAndAddress);	
SnailMail snail = newSnail(person);
Idiom #6
Idiom: unions of values
Imagine we want to write down the signature of Set.union() in Java:

!

//Java	
interface Set<T> {	
!
public <U super T> Set<U> union(Set<? extends U> set);	
}

!

This doesn’t actually compile since Java doesn’t have lower bounded type
parameters. (The equivalent thing would work in Scala though.)
Set<Foo> setOfFoo = ... ; 	
Set<Bar> setOfBar = ... ;	

!
Set<Object> setOfFoosAndBars = setOfFoo.union(setOfBar);
Idiom #6
Idiom: unions of values
Unions of values correspond to unions of types!

!

interface Set<These> {	
shared formal Set<These|Those> union<Those>(Set<Those> set);	
!
}

!
Exactly the right type pops out automatically.
Set<Foo> setOfFoo = ... ; 	
Set<Bar> setOfBar = ... ;	

!
Set<Foo|Bar> setOfFoosAndBars = setOfFoo | setOfBar;
Idiom #7
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 #7
Idiom: intersections of values
Intersections of values correspond to intersections of types!

!

interface Set<These> {	
shared formal Set<These&Those> intersection<Those>(Set<Those> set);	
!
}

!
Again, exactly the right type pops out automatically.
Set<Foo> setOfFoo = ... ; 	
Set<Bar> setOfBar = ... ;	

!
Set<Foo&Bar> setOfFooBars = setOfFoo & setOfBar;
Idiom #7
Idiom: intersections of values
Example: the coalesce() function eliminates null elements from an Iterable
object.

!
{Element&Object*} coalesce<Element>({Element*} elements) 	
=> { for (e in elements) if (exists e) e };
!

Exactly the right type pops out automatically.

!

{String?*} words = { “hello”, null, “world” };	
{String*} strings = coalesce(words);
!

!
(Even though I’m explicitly writing in the types, I could have let them be inferred.)
Idiom #8
Idiom: empty vs nonempty
Problem: the max() function can return null, but only when the Iterable object
might be empty.

!

shared Value? max<Value>({Value*} values) 	
!
given Value satisfies Comparable<Value> { ... }

!
What if we know it’s nonempty? A separate function?

!
shared Value maxNonempty<Value>({Value+} values) 	
!
given Value satisfies Comparable<Value> { ... }

!
This doesn’t let us abstract.
Idiom #8
Idiom: empty vs nonempty
Solution: the Iterable object has an extra type parameter.

!
shared Absent|Value max<Value,Absent>(Iterable<Value,Absent> values) 	
!
given Value satisfies Comparable<Value>	
given Absent satisfies Null { ... }

!

Exactly the right type pops out automatically.
Null maxOfNone = max {};	
String maxOfSome = max { “hello”, “world” };	

!
{String*} noneOrSome = ... ;	
String? max = max(noneOrSome);
Idiom #9
Idiom: abstract over function types
Example: the compose() function composes functions.

!
X compose<X,Y,A>(X(Y) x, Y(A) y)(A a)	
!
=> x(y(a));	

!
But this is not quite as general as it could be!

!

value printSqrt = compose(print,sqrt);	

!
What about functions with multiple parameters?
value printSum = compose(print,plus<Float>);
Idiom #9
Idiom: abstract over function types
Solution: abstract over unknown tuple type.

!
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)));

!
!

A little uglier, but does the job!
Anything(Float,Float) printSum 	
= compose(print,plus<Float>);
Idiom #10
Idiom: discovery
Example: auto-discover classes annotated test.
shared test class IdiomTests() { ... }
!

We use the Ceylon metamodel:
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());	
}	
}	
}

Más contenido relacionado

La actualidad más candente

Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Danial Virk
 
String handling session 5
String handling session 5String handling session 5
String handling session 5Raja Sekhar
 
Monad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsMonad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsPhilip Schwarz
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of FlatteryJosé Paumard
 
Java string handling
Java string handlingJava string handling
Java string handlingSalman Khan
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)Ravi Kant Sahu
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming LanguageNicolò Calcavecchia
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java ProgrammersMike Bowler
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic JavascriptBunlong Van
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basicsmsemenistyi
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introductionGonçalo Silva
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Aaron Gustafson
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of FlatteryJosé Paumard
 

La actualidad más candente (19)

Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)Strings In OOP(Object oriented programming)
Strings In OOP(Object oriented programming)
 
String handling session 5
String handling session 5String handling session 5
String handling session 5
 
Monad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsMonad as functor with pair of natural transformations
Monad as functor with pair of natural transformations
 
Strings in Java
Strings in JavaStrings in Java
Strings in Java
 
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM LanguageCodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
CodeFest 2010. Иноземцев И. — Fantom. Cross-VM Language
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 
Java string handling
Java string handlingJava string handling
Java string handling
 
String handling(string class)
String handling(string class)String handling(string class)
String handling(string class)
 
Introduction to Ruby Programming Language
Introduction to Ruby Programming LanguageIntroduction to Ruby Programming Language
Introduction to Ruby Programming Language
 
Ruby For Java Programmers
Ruby For Java ProgrammersRuby For Java Programmers
Ruby For Java Programmers
 
JavaScript Basics
JavaScript BasicsJavaScript Basics
JavaScript Basics
 
Basic Javascript
Basic JavascriptBasic Javascript
Basic Javascript
 
Javascript Basics
Javascript BasicsJavascript Basics
Javascript Basics
 
String Handling
String HandlingString Handling
String Handling
 
Ruby — An introduction
Ruby — An introductionRuby — An introduction
Ruby — An introduction
 
Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]Fundamental JavaScript [UTC, March 2014]
Fundamental JavaScript [UTC, March 2014]
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
The Sincerest Form of Flattery
The Sincerest Form of FlatteryThe Sincerest Form of Flattery
The Sincerest Form of Flattery
 

Destacado

Ceylon module repositories by Aleš Justin
Ceylon module repositories by Aleš JustinCeylon module repositories by Aleš Justin
Ceylon module repositories by Aleš JustinUnFroMage
 
Cayla and Vert.x in Ceylon, by Gavin King
Cayla and Vert.x in Ceylon, by Gavin KingCayla and Vert.x in Ceylon, by Gavin King
Cayla and Vert.x in Ceylon, by Gavin KingUnFroMage
 
Ceylon SDK by Stéphane Épardaud
Ceylon SDK by Stéphane ÉpardaudCeylon SDK by Stéphane Épardaud
Ceylon SDK by Stéphane ÉpardaudUnFroMage
 
Ceylon.test by Thomáš Hradec
Ceylon.test by Thomáš HradecCeylon.test by Thomáš Hradec
Ceylon.test by Thomáš HradecUnFroMage
 
Ceylon introduction by Stéphane Épardaud
Ceylon introduction by Stéphane ÉpardaudCeylon introduction by Stéphane Épardaud
Ceylon introduction by Stéphane ÉpardaudUnFroMage
 
Ceylon.build by Loïc Rouchon
Ceylon.build by Loïc RouchonCeylon.build by Loïc Rouchon
Ceylon.build by Loïc RouchonUnFroMage
 
Ceylon/Java interop by Tako Schotanus
Ceylon/Java interop by Tako SchotanusCeylon/Java interop by Tako Schotanus
Ceylon/Java interop by Tako SchotanusUnFroMage
 

Destacado (7)

Ceylon module repositories by Aleš Justin
Ceylon module repositories by Aleš JustinCeylon module repositories by Aleš Justin
Ceylon module repositories by Aleš Justin
 
Cayla and Vert.x in Ceylon, by Gavin King
Cayla and Vert.x in Ceylon, by Gavin KingCayla and Vert.x in Ceylon, by Gavin King
Cayla and Vert.x in Ceylon, by Gavin King
 
Ceylon SDK by Stéphane Épardaud
Ceylon SDK by Stéphane ÉpardaudCeylon SDK by Stéphane Épardaud
Ceylon SDK by Stéphane Épardaud
 
Ceylon.test by Thomáš Hradec
Ceylon.test by Thomáš HradecCeylon.test by Thomáš Hradec
Ceylon.test by Thomáš Hradec
 
Ceylon introduction by Stéphane Épardaud
Ceylon introduction by Stéphane ÉpardaudCeylon introduction by Stéphane Épardaud
Ceylon introduction by Stéphane Épardaud
 
Ceylon.build by Loïc Rouchon
Ceylon.build by Loïc RouchonCeylon.build by Loïc Rouchon
Ceylon.build by Loïc Rouchon
 
Ceylon/Java interop by Tako Schotanus
Ceylon/Java interop by Tako SchotanusCeylon/Java interop by Tako Schotanus
Ceylon/Java interop by Tako Schotanus
 

Similar a Ceylon idioms by Gavin King

JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript TutorialBui Kiet
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftMichele Titolo
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to ProgrammingCindy Royal
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Languagezone
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoobirbal
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming LanguageRaghavan Mohan
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de JavascriptBernard Loire
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. ExperienceMike Fogus
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameAntony Stubbs
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingKeshav Kumar
 

Similar a Ceylon idioms by Gavin King (20)

JavaScript Tutorial
JavaScript  TutorialJavaScript  Tutorial
JavaScript Tutorial
 
Cocoa Design Patterns in Swift
Cocoa Design Patterns in SwiftCocoa Design Patterns in Swift
Cocoa Design Patterns in Swift
 
Handout - Introduction to Programming
Handout - Introduction to ProgrammingHandout - Introduction to Programming
Handout - Introduction to Programming
 
Ruby Basics
Ruby BasicsRuby Basics
Ruby Basics
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Javascript
JavascriptJavascript
Javascript
 
Ruby Gotchas
Ruby GotchasRuby Gotchas
Ruby Gotchas
 
The Java Script Programming Language
The  Java Script  Programming  LanguageThe  Java Script  Programming  Language
The Java Script Programming Language
 
Javascript by Yahoo
Javascript by YahooJavascript by Yahoo
Javascript by Yahoo
 
The JavaScript Programming Language
The JavaScript Programming LanguageThe JavaScript Programming Language
The JavaScript Programming Language
 
Javascript
JavascriptJavascript
Javascript
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Naïveté vs. Experience
Naïveté vs. ExperienceNaïveté vs. Experience
Naïveté vs. Experience
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love GameScala Language Intro - Inspired by the Love Game
Scala Language Intro - Inspired by the Love Game
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 
JAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programmingJAVA Tutorial- Do's and Don'ts of Java programming
JAVA Tutorial- Do's and Don'ts of Java programming
 

Último

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 

Último (20)

08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 

Ceylon idioms by Gavin King

  • 1. Ten Ceylon Idioms Gavin King - Red Hat profiles.google.com/gavin.king ceylon-lang.org !
  • 2. “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
  • 3. Idiom #1 Idiom: functions with multiple outcomes For example, an operation might return a Person, an Org, or nothing. //Java ! Object findByName(String name) throws NotFoundException { ... } ! We can handle the different outcomes using instanceof, type casts, and catch: try { Object result = findByName(name); if (result instanceof Org) { Org org = (Org) result; ... } if (result instanceof Person) { Person person = (Person) result; ... } } catch (NotFoundException nfe) { ... }
  • 4. Idiom #1 Idiom: functions with multiple outcomes A function with more than one “outcome” can be defined using a union type. ! Org|Person|NotFound findByName(String name) => ... ; ! We can handle the various outcomes using switch: value result = findByName(name); switch (result) case (is Org|Person) { ... } case (is NotFound) { ... }
  • 5. Item? get(Key key) Idiom #2 Idiom: functions returning null Example: retrieving an element from a map. (Special case of multiple outcomes!) ! Item? get(Key key) => ... ; ! For a union type of form Null|Item, we have some special syntax sugar: value map = HashMap { “enrique”->cst, “tom”->gmt, “ross”->pst }; Timezone tz = map[name] else cet;
  • 6. 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. ! if (name in map) { assert (exists tz = map[name]); ! return ZonedTime(time, tz); } ! A different way to write this code: ! if (exists tz = map[name]) { return ZonedTime(time, tz); }
  • 7. Idiom #3 Idiom: overloading For example, an operation might apply to an Integer, or to a Float. ! //Java Float sqrt(Float ! number) { ... } Float sqrt(Integer number) { ... } ! Actually two different, unrelated operations. !
  • 8. Idiom #3 Idiom: overloading A function parameter can be defined using a union type. ! Float sqrt(Float|Integer number) { switch (number) ! case (is Float) { ... } case (is Integer) { ... } ! } ! Now we have a single operation: Float fourthRoot(Float|Integer number) => sqrt(sqrt(number)); ! And we can obtain a reference to it: Float(Float|Integer) sqrtFun = sqrt;
  • 9. Idiom #4 Idiom: multiple return values For example, an operation might return a Name //Java class NameAndAddress { ... } ! and an Address. ! ! NameAndAddress getNameAndAddress(Person person) { ! return new NameAndAddress(new Name(person.getFirst(), person.getLast()), person.getHome().getAddress()); ! } ! We have to define a class. !
  • 10. Idiom #4 Idiom: multiple return values A function can be defined to return a tuple type. [Name,Address] getNameAndAddress(Person person) ! => [Name(person.first, person.last), person.home.address]; ! Now a caller can extract the individual return values: value nameAndAddress = ! getNameAndAddress(person); Name name = nameAndAddress[0]; ! Address address = nameAndAddress[1]; ! What about other indexes? Null missing = nameAndAddress[3]; Name|Address|Null val = nameAndAddress[index];
  • 11. Idiom #5 Idiom: spreading tuple return values Imagine we want to pass the result of getNameAndAddress() to another function or class initializer. ! class SnailMail(Name name, Address address) { ... } ! We can use the spread operator, *, like in Groovy: ! value snail = SnailMail(*getNameAndAddress(person)); ! Or we can work at the function level, using unflatten() SnailMail(Person) newSnail = compose(unflatten(SnailMail), getNameAndAddress); SnailMail snail = newSnail(person);
  • 12. Idiom #6 Idiom: unions of values Imagine we want to write down the signature of Set.union() in Java: ! //Java interface Set<T> { ! public <U super T> Set<U> union(Set<? extends U> set); } ! This doesn’t actually compile since Java doesn’t have lower bounded type parameters. (The equivalent thing would work in Scala though.) Set<Foo> setOfFoo = ... ; Set<Bar> setOfBar = ... ; ! Set<Object> setOfFoosAndBars = setOfFoo.union(setOfBar);
  • 13. Idiom #6 Idiom: unions of values Unions of values correspond to unions of types! ! interface Set<These> { shared formal Set<These|Those> union<Those>(Set<Those> set); ! } ! Exactly the right type pops out automatically. Set<Foo> setOfFoo = ... ; Set<Bar> setOfBar = ... ; ! Set<Foo|Bar> setOfFoosAndBars = setOfFoo | setOfBar;
  • 14. Idiom #7 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.
  • 15. Idiom #7 Idiom: intersections of values Intersections of values correspond to intersections of types! ! interface Set<These> { shared formal Set<These&Those> intersection<Those>(Set<Those> set); ! } ! Again, exactly the right type pops out automatically. Set<Foo> setOfFoo = ... ; Set<Bar> setOfBar = ... ; ! Set<Foo&Bar> setOfFooBars = setOfFoo & setOfBar;
  • 16. Idiom #7 Idiom: intersections of values Example: the coalesce() function eliminates null elements from an Iterable object. ! {Element&Object*} coalesce<Element>({Element*} elements) => { for (e in elements) if (exists e) e }; ! Exactly the right type pops out automatically. ! {String?*} words = { “hello”, null, “world” }; {String*} strings = coalesce(words); ! ! (Even though I’m explicitly writing in the types, I could have let them be inferred.)
  • 17. Idiom #8 Idiom: empty vs nonempty Problem: the max() function can return null, but only when the Iterable object might be empty. ! shared Value? max<Value>({Value*} values) ! given Value satisfies Comparable<Value> { ... } ! What if we know it’s nonempty? A separate function? ! shared Value maxNonempty<Value>({Value+} values) ! given Value satisfies Comparable<Value> { ... } ! This doesn’t let us abstract.
  • 18. Idiom #8 Idiom: empty vs nonempty Solution: the Iterable object has an extra type parameter. ! shared Absent|Value max<Value,Absent>(Iterable<Value,Absent> values) ! given Value satisfies Comparable<Value> given Absent satisfies Null { ... } ! Exactly the right type pops out automatically. Null maxOfNone = max {}; String maxOfSome = max { “hello”, “world” }; ! {String*} noneOrSome = ... ; String? max = max(noneOrSome);
  • 19. Idiom #9 Idiom: abstract over function types Example: the compose() function composes functions. ! X compose<X,Y,A>(X(Y) x, Y(A) y)(A a) ! => x(y(a)); ! But this is not quite as general as it could be! ! value printSqrt = compose(print,sqrt); ! What about functions with multiple parameters? value printSum = compose(print,plus<Float>);
  • 20. Idiom #9 Idiom: abstract over function types Solution: abstract over unknown tuple type. ! 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))); ! ! A little uglier, but does the job! Anything(Float,Float) printSum = compose(print,plus<Float>);
  • 21. Idiom #10 Idiom: discovery Example: auto-discover classes annotated test. shared test class IdiomTests() { ... } ! We use the Ceylon metamodel: 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()); } } }