SlideShare une entreprise Scribd logo
1  sur  21
Télécharger pour lire hors ligne
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());	
}	
}	
}

Contenu connexe

Tendances

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
 

Tendances (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
 

En vedette

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
 

En vedette (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
 

Similaire à 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
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de JavascriptBernard Loire
 
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
 
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
 

Similaire à 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
 
Les origines de Javascript
Les origines de JavascriptLes origines de Javascript
Les origines de Javascript
 
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
 
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
 

Dernier

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProduct Anonymous
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024The Digital Insurer
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MIND CTI
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 

Dernier (20)

Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024Manulife - Insurer Innovation Award 2024
Manulife - Insurer Innovation Award 2024
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024MINDCTI Revenue Release Quarter One 2024
MINDCTI Revenue Release Quarter One 2024
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 

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()); } } }