SlideShare a Scribd company logo
Brian J. Cardiff
bcardiff@manas.tech
@CACIC2019@CrystalLanguage
Juan Wajnerman
waj@manas.tech
https://man.as/cacic2019
Fundamentos, objetivos y desafíos
Queremos un lenguaje
● Expresivo y seguro para el programador
● Cómodo para la máquina
Crystal
Syntaxis amena
# file: beetle.cr
3.times do
puts "Beetlejuice!"
end
$ crystal beetle.cr
Beetlejuice!
Beetlejuice!
Beetlejuice!
● Preludio implícito
● Reapertura de clases: Int.times
● Bloques
● Métodos top-level: puts
$ crystal build beetle.cr -o beetle
$ ./beetle
Beetlejuice!
Beetlejuice!
Beetlejuice!
$ otool -L ./beetle
./bettle:
/usr/lib/libpcre.0.dylib (compatibility version 1.0.0, current version
1.1.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current
version 1252.250.1)
Compilado
$ crystal build --emit llvm-ir --no-debug beetle.cr
$ cat beetle.ll
@"'Beetlejuice!'" = private constant { i32, i32, i32, [13 x i8] } { i32 1, i32 12, i32 12,
[13 x i8] c"Beetlejuice!00" }
define void @__crystal_main(i32 %argc, i8** %argv) {
alloca:
%i = alloca i32
; ...
while:
%68 = load i32, i32* %i
%69 = icmp slt i32 %68, 3
br i1 %69, label %body, label %exit
body:
Compilado (via LLVM)
$ crystal build --emit asm --no-debug beetle.cr
$ cat beetle.s
LBB0_60:
cmpl $3, 52(%rsp)
jge LBB0_62
leaq "l_'Beetlejuice!'"(%rip), %rax
movq %rax, %rdi
callq "_*puts<String>:Nil"
movl 52(%rsp), %ecx
addl $1, %ecx
movl %ecx, 52(%rsp)
jmp LBB0_60
LBB0_62:
Compilado (via LLVM)
Evitar errores en runtime
puts "Hello Beetlejuice !".upper_case
$ crystal build beetle.cr
In beetle.cr:2:27
2 | puts "Hello Beetlejuice !".upper_case
^---------
Error: undefined method 'upper_case' for String
puts "Hello Beetlejuice !".upcase
$ crystal build beetle.cr
$ ./beetle
Hello Beetlejuice !
Evitar errores en runtime
# file: input.cr
name = gets
puts "Hello #{name.upcase} !"
$ crystal build input.cr
Evitar errores en runtime
# file: input.cr
name = gets
puts "Hello #{name.upcase} !"
$ crystal build input.cr
In input.cr:3:20
3 | puts "Hello #{name.upcase} !"
^-----
Error: undefined method 'upcase' for Nil (compile-time type is (String | Nil))
Evitar errores en runtime
def sum(a, b)
a + b
end
sum "foo", "bar" # => "foobar"
sum 40, 2 # => 42
sum "foo", 0 # => Compile time error
Pero sin ser tan tercos
● Instanciación lazy de métodos
● Restricciones de tipos opcionales
class Object
macro property(name)
@{{name.var}} : {{name.type}}
def {{name.var}} : {{name.type}}
@{{name.var}}
end
def {{name.var}}=(@{{name.var}} : {{name.type}})
end
end
end
Metaprogramación
class Human
property name : String
def initialize(@name)
end
end
class Dragon
def meet(h : Human)
puts "Bite"
end
def meet(d : Dragon)
puts "Play"
end
end
class Human
def meet(h : Human)
puts "Hi #{h.name}, I'm #{name}"
end
def meet(d : Dragon)
puts "Watch & train #{d.name}"
end
end
Multi-dispatch & “duck-typing”
creatures = [Human.new("Hiccup"), Human.new("Astrid"),
Dragon.new("Toothless"), Dragon.new("Fireworm")]
a, b = creatures.sample(2) # => a, b : Human | Dragon
print "#{a.name} meeting #{b.name}: "
a.meet(b)
Concurrencia
Múltiples trazas de ejecución compartiendo recursos:
● CPU
● I/O
● Memoria
channel = Channel(Int32).new
total_lines = 0
files = Dir.glob("*.cr")
files.each do |f|
spawn do
lines = File.read(f).lines.size
channel.send lines
end
end
files.size.times do
total_lines += channel.receive
end
puts total_lines
Concurrencia
● Fibers (coroutines)
● Managed thread(s) worker(s)
● Blocking API (no callbacks)
“Do not communicate by sharing memory;
instead, share memory by communicating.”
Effective Go
https://golang.org/doc/effective_go.html#sharing
Fibers
Scheduler
Fibers
Event Loop
● de usuario
● de sistema
● IO
● timers
d1 = HTTP::Client.get("http://...")
d2 = HTTP::Client.get("http://...")
d3 = HTTP::Client.get("http://...")
Fibers vs. Callbacks
fetch("http://...", (d1) => {
fetch("http://...", (d2) => {
fetch("http://...", (d3) => {
})
})
})
Canales
chSend Receivech.send(123) ch.receive
ch = Channel(Int32).new
Canales
Recolectar
Resultados
ch1
Calcular
Celda
Calcular
Celda
Calcular
Celda
Calcular
Celda
ch2
Repartir
Celdas
Multiplicar matrices:
Elecciones en Crystal
● Syntaxis amena
● Compilado
● Evitar errores en runtime cuando se pueda
● Inferencia de tipos, Multi-dispatch y “duck-typing”
● Modelo de programación concurrente
● Metaprogramación
● Promover buenas prácticas de uso de recursos
● Integración con C
● from a DB to JSON with Crystal
○ https://manas.tech/blog/2017/01/16/from-a-db-to-json-with-crystal/
○ https://github.com/crystal-lang/crystal-db
● https://kemalcr.com/
● https://amberframework.org/
● https://luckyframework.org
● samples/2048.cr https://github.com/crystal-lang/crystal/tree/master/samples
● sdl raytracer https://github.com/asterite/crystal_sdl2_examples
● nes https://github.com/asterite/nes.cr
Apps & Frameworks
crystal-lang.org
¿Dónde?
Brian J. Cardiff
bcardiff@manas.tech
¡gracias!
Juan Wajnerman
waj@manas.tech

More Related Content

What's hot

Perl 5.10
Perl 5.10Perl 5.10
Perl 5.10
acme
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
Peter Higgins
 
drb09
drb09drb09
drb09
mseki
 
Rochester on Rails: Introduction to Ruby
Rochester on Rails: Introduction to RubyRochester on Rails: Introduction to Ruby
Rochester on Rails: Introduction to Ruby
Jason Morrison
 
Modern Perl
Modern PerlModern Perl
Modern Perl
Marcos Rebelo
 
Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)
Kang-min Liu
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
Tiago Peczenyj
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
Open Gurukul
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
Wen-Tien Chang
 
Ruby 101
Ruby 101Ruby 101
Ruby 101
Harisankar P S
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
Wes Oldenbeuving
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
Abhay Sapru
 
Smalltalk on rubinius
Smalltalk on rubiniusSmalltalk on rubinius
Smalltalk on rubinius
Konstantin Haase
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012
xSawyer
 
YAPC::Tiny Introduction
YAPC::Tiny IntroductionYAPC::Tiny Introduction
YAPC::Tiny Introduction
Kang-min Liu
 
Vim Hacks (OSSF)
Vim Hacks (OSSF)Vim Hacks (OSSF)
Vim Hacks (OSSF)
Lin Yo-An
 
DSL Quest: A WAT Safari - PuppetConf 2013
DSL Quest: A WAT Safari - PuppetConf 2013DSL Quest: A WAT Safari - PuppetConf 2013
DSL Quest: A WAT Safari - PuppetConf 2013
Puppet
 
#safaDojo - Coding Dojo Go lang
#safaDojo - Coding Dojo Go lang#safaDojo - Coding Dojo Go lang
#safaDojo - Coding Dojo Go lang
Marcelo Andrade
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
Lin Yo-An
 

What's hot (20)

Perl 5.10
Perl 5.10Perl 5.10
Perl 5.10
 
Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.Your Library Sucks, and why you should use it.
Your Library Sucks, and why you should use it.
 
drb09
drb09drb09
drb09
 
Rochester on Rails: Introduction to Ruby
Rochester on Rails: Introduction to RubyRochester on Rails: Introduction to Ruby
Rochester on Rails: Introduction to Ruby
 
Modern Perl
Modern PerlModern Perl
Modern Perl
 
Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)Learning From Ruby (Yapc Asia)
Learning From Ruby (Yapc Asia)
 
Perl Moderno
Perl ModernoPerl Moderno
Perl Moderno
 
OpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell ScriptingOpenGurukul : Language : Shell Scripting
OpenGurukul : Language : Shell Scripting
 
Ruby 程式語言入門導覽
Ruby 程式語言入門導覽Ruby 程式語言入門導覽
Ruby 程式語言入門導覽
 
Ruby 101
Ruby 101Ruby 101
Ruby 101
 
An introduction to Ruby
An introduction to RubyAn introduction to Ruby
An introduction to Ruby
 
Unix shell scripting basics
Unix shell scripting basicsUnix shell scripting basics
Unix shell scripting basics
 
Smalltalk on rubinius
Smalltalk on rubiniusSmalltalk on rubinius
Smalltalk on rubinius
 
Moose - YAPC::NA 2012
Moose - YAPC::NA 2012Moose - YAPC::NA 2012
Moose - YAPC::NA 2012
 
YAPC::Tiny Introduction
YAPC::Tiny IntroductionYAPC::Tiny Introduction
YAPC::Tiny Introduction
 
Vim Hacks (OSSF)
Vim Hacks (OSSF)Vim Hacks (OSSF)
Vim Hacks (OSSF)
 
DSL Quest: A WAT Safari - PuppetConf 2013
DSL Quest: A WAT Safari - PuppetConf 2013DSL Quest: A WAT Safari - PuppetConf 2013
DSL Quest: A WAT Safari - PuppetConf 2013
 
#safaDojo - Coding Dojo Go lang
#safaDojo - Coding Dojo Go lang#safaDojo - Coding Dojo Go lang
#safaDojo - Coding Dojo Go lang
 
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
Puppet Camp Chicago 2014: Smoothing Troubles With Custom Types and Providers ...
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
 

Similar to Crystal: Fundamentos, objetivos y desafios - Cacic 2019

Language supports it
Language supports itLanguage supports it
Language supports it
Niranjan Paranjape
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
RORLAB
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
Wen-Tien Chang
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
Marc Chung
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
Ígor Bonadio
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
Christopher Spring
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
loffenauer
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)
Bozhidar Batsov
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介
Wen-Tien Chang
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
Bhavin Javia
 
TechDays - IronRuby
TechDays - IronRubyTechDays - IronRuby
TechDays - IronRuby
Ben Hall
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRuby
Frederic Jean
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
Jano Suchal
 
HTML5 JavaScript Interfaces
HTML5 JavaScript InterfacesHTML5 JavaScript Interfaces
HTML5 JavaScript Interfaces
Aaron Gustafson
 
Exploring Code with Pry!
Exploring Code with Pry!Exploring Code with Pry!
Exploring Code with Pry!
Clayton Parker
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
Astrails
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
Aaron Patterson
 
Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivo
Fabio Kung
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
alexismidon
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
Troy Miles
 

Similar to Crystal: Fundamentos, objetivos y desafios - Cacic 2019 (20)

Language supports it
Language supports itLanguage supports it
Language supports it
 
Active Support Core Extensions (1)
Active Support Core Extensions (1)Active Support Core Extensions (1)
Active Support Core Extensions (1)
 
Ruby 入門 第一次就上手
Ruby 入門 第一次就上手Ruby 入門 第一次就上手
Ruby 入門 第一次就上手
 
Hacking with ruby2ruby
Hacking with ruby2rubyHacking with ruby2ruby
Hacking with ruby2ruby
 
Ruby - Uma Introdução
Ruby - Uma IntroduçãoRuby - Uma Introdução
Ruby - Uma Introdução
 
jRuby: The best of both worlds
jRuby: The best of both worldsjRuby: The best of both worlds
jRuby: The best of both worlds
 
2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws2007 09 10 Fzi Training Groovy Grails V Ws
2007 09 10 Fzi Training Groovy Grails V Ws
 
Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)Модерни езици за програмиране за JVM (2011)
Модерни езици за програмиране за JVM (2011)
 
Ruby 程式語言簡介
Ruby 程式語言簡介Ruby 程式語言簡介
Ruby 程式語言簡介
 
Write your Ruby in Style
Write your Ruby in StyleWrite your Ruby in Style
Write your Ruby in Style
 
TechDays - IronRuby
TechDays - IronRubyTechDays - IronRuby
TechDays - IronRuby
 
Quick Intro To JRuby
Quick Intro To JRubyQuick Intro To JRuby
Quick Intro To JRuby
 
Postobjektové programovanie v Ruby
Postobjektové programovanie v RubyPostobjektové programovanie v Ruby
Postobjektové programovanie v Ruby
 
HTML5 JavaScript Interfaces
HTML5 JavaScript InterfacesHTML5 JavaScript Interfaces
HTML5 JavaScript Interfaces
 
Exploring Code with Pry!
Exploring Code with Pry!Exploring Code with Pry!
Exploring Code with Pry!
 
Ruby is an Acceptable Lisp
Ruby is an Acceptable LispRuby is an Acceptable Lisp
Ruby is an Acceptable Lisp
 
Having Fun Programming!
Having Fun Programming!Having Fun Programming!
Having Fun Programming!
 
Ruby, muito mais que reflexivo
Ruby, muito mais que reflexivoRuby, muito mais que reflexivo
Ruby, muito mais que reflexivo
 
Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012Buildr In Action @devoxx france 2012
Buildr In Action @devoxx france 2012
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 

Recently uploaded

International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
gerogepatton
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
SUTEJAS
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
MDSABBIROJJAMANPAYEL
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
wisnuprabawa3
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
Madan Karki
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
jpsjournal1
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
Victor Morales
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
KrishnaveniKrishnara1
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
co23btech11018
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
camseq
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
University of Maribor
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
171ticu
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
zubairahmad848137
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
rpskprasana
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
IJECEIAES
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
IJECEIAES
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
Aditya Rajan Patra
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
VICTOR MAESTRE RAMIREZ
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
Las Vegas Warehouse
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
NidhalKahouli2
 

Recently uploaded (20)

International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...International Conference on NLP, Artificial Intelligence, Machine Learning an...
International Conference on NLP, Artificial Intelligence, Machine Learning an...
 
Understanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine LearningUnderstanding Inductive Bias in Machine Learning
Understanding Inductive Bias in Machine Learning
 
Properties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptxProperties Railway Sleepers and Test.pptx
Properties Railway Sleepers and Test.pptx
 
New techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdfNew techniques for characterising damage in rock slopes.pdf
New techniques for characterising damage in rock slopes.pdf
 
spirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptxspirit beverages ppt without graphics.pptx
spirit beverages ppt without graphics.pptx
 
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECTCHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
CHINA’S GEO-ECONOMIC OUTREACH IN CENTRAL ASIAN COUNTRIES AND FUTURE PROSPECT
 
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressionsKuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
KuberTENes Birthday Bash Guadalajara - K8sGPT first impressions
 
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.pptUnit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
Unit-III-ELECTROCHEMICAL STORAGE DEVICES.ppt
 
Computational Engineering IITH Presentation
Computational Engineering IITH PresentationComputational Engineering IITH Presentation
Computational Engineering IITH Presentation
 
Modelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdfModelagem de um CSTR com reação endotermica.pdf
Modelagem de um CSTR com reação endotermica.pdf
 
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
Presentation of IEEE Slovenia CIS (Computational Intelligence Society) Chapte...
 
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样官方认证美国密歇根州立大学毕业证学位证书原版一模一样
官方认证美国密歇根州立大学毕业证学位证书原版一模一样
 
Casting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdfCasting-Defect-inSlab continuous casting.pdf
Casting-Defect-inSlab continuous casting.pdf
 
CSM Cloud Service Management Presentarion
CSM Cloud Service Management PresentarionCSM Cloud Service Management Presentarion
CSM Cloud Service Management Presentarion
 
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...
 
Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...Advanced control scheme of doubly fed induction generator for wind turbine us...
Advanced control scheme of doubly fed induction generator for wind turbine us...
 
Recycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part IIIRecycled Concrete Aggregate in Construction Part III
Recycled Concrete Aggregate in Construction Part III
 
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student MemberIEEE Aerospace and Electronic Systems Society as a Graduate Student Member
IEEE Aerospace and Electronic Systems Society as a Graduate Student Member
 
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have oneISPM 15 Heat Treated Wood Stamps and why your shipping must have one
ISPM 15 Heat Treated Wood Stamps and why your shipping must have one
 
basic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdfbasic-wireline-operations-course-mahmoud-f-radwan.pdf
basic-wireline-operations-course-mahmoud-f-radwan.pdf
 

Crystal: Fundamentos, objetivos y desafios - Cacic 2019

  • 1. Brian J. Cardiff bcardiff@manas.tech @CACIC2019@CrystalLanguage Juan Wajnerman waj@manas.tech https://man.as/cacic2019 Fundamentos, objetivos y desafíos
  • 2. Queremos un lenguaje ● Expresivo y seguro para el programador ● Cómodo para la máquina Crystal
  • 3. Syntaxis amena # file: beetle.cr 3.times do puts "Beetlejuice!" end $ crystal beetle.cr Beetlejuice! Beetlejuice! Beetlejuice! ● Preludio implícito ● Reapertura de clases: Int.times ● Bloques ● Métodos top-level: puts
  • 4. $ crystal build beetle.cr -o beetle $ ./beetle Beetlejuice! Beetlejuice! Beetlejuice! $ otool -L ./beetle ./bettle: /usr/lib/libpcre.0.dylib (compatibility version 1.0.0, current version 1.1.0) /usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 1252.250.1) Compilado
  • 5. $ crystal build --emit llvm-ir --no-debug beetle.cr $ cat beetle.ll @"'Beetlejuice!'" = private constant { i32, i32, i32, [13 x i8] } { i32 1, i32 12, i32 12, [13 x i8] c"Beetlejuice!00" } define void @__crystal_main(i32 %argc, i8** %argv) { alloca: %i = alloca i32 ; ... while: %68 = load i32, i32* %i %69 = icmp slt i32 %68, 3 br i1 %69, label %body, label %exit body: Compilado (via LLVM)
  • 6. $ crystal build --emit asm --no-debug beetle.cr $ cat beetle.s LBB0_60: cmpl $3, 52(%rsp) jge LBB0_62 leaq "l_'Beetlejuice!'"(%rip), %rax movq %rax, %rdi callq "_*puts<String>:Nil" movl 52(%rsp), %ecx addl $1, %ecx movl %ecx, 52(%rsp) jmp LBB0_60 LBB0_62: Compilado (via LLVM)
  • 7. Evitar errores en runtime puts "Hello Beetlejuice !".upper_case $ crystal build beetle.cr In beetle.cr:2:27 2 | puts "Hello Beetlejuice !".upper_case ^--------- Error: undefined method 'upper_case' for String
  • 8. puts "Hello Beetlejuice !".upcase $ crystal build beetle.cr $ ./beetle Hello Beetlejuice ! Evitar errores en runtime
  • 9. # file: input.cr name = gets puts "Hello #{name.upcase} !" $ crystal build input.cr Evitar errores en runtime
  • 10. # file: input.cr name = gets puts "Hello #{name.upcase} !" $ crystal build input.cr In input.cr:3:20 3 | puts "Hello #{name.upcase} !" ^----- Error: undefined method 'upcase' for Nil (compile-time type is (String | Nil)) Evitar errores en runtime
  • 11. def sum(a, b) a + b end sum "foo", "bar" # => "foobar" sum 40, 2 # => 42 sum "foo", 0 # => Compile time error Pero sin ser tan tercos ● Instanciación lazy de métodos ● Restricciones de tipos opcionales
  • 12. class Object macro property(name) @{{name.var}} : {{name.type}} def {{name.var}} : {{name.type}} @{{name.var}} end def {{name.var}}=(@{{name.var}} : {{name.type}}) end end end Metaprogramación class Human property name : String def initialize(@name) end end
  • 13. class Dragon def meet(h : Human) puts "Bite" end def meet(d : Dragon) puts "Play" end end class Human def meet(h : Human) puts "Hi #{h.name}, I'm #{name}" end def meet(d : Dragon) puts "Watch & train #{d.name}" end end Multi-dispatch & “duck-typing” creatures = [Human.new("Hiccup"), Human.new("Astrid"), Dragon.new("Toothless"), Dragon.new("Fireworm")] a, b = creatures.sample(2) # => a, b : Human | Dragon print "#{a.name} meeting #{b.name}: " a.meet(b)
  • 14. Concurrencia Múltiples trazas de ejecución compartiendo recursos: ● CPU ● I/O ● Memoria
  • 15. channel = Channel(Int32).new total_lines = 0 files = Dir.glob("*.cr") files.each do |f| spawn do lines = File.read(f).lines.size channel.send lines end end files.size.times do total_lines += channel.receive end puts total_lines Concurrencia ● Fibers (coroutines) ● Managed thread(s) worker(s) ● Blocking API (no callbacks) “Do not communicate by sharing memory; instead, share memory by communicating.” Effective Go https://golang.org/doc/effective_go.html#sharing
  • 16. Fibers Scheduler Fibers Event Loop ● de usuario ● de sistema ● IO ● timers
  • 17. d1 = HTTP::Client.get("http://...") d2 = HTTP::Client.get("http://...") d3 = HTTP::Client.get("http://...") Fibers vs. Callbacks fetch("http://...", (d1) => { fetch("http://...", (d2) => { fetch("http://...", (d3) => { }) }) })
  • 20. Elecciones en Crystal ● Syntaxis amena ● Compilado ● Evitar errores en runtime cuando se pueda ● Inferencia de tipos, Multi-dispatch y “duck-typing” ● Modelo de programación concurrente ● Metaprogramación ● Promover buenas prácticas de uso de recursos ● Integración con C
  • 21. ● from a DB to JSON with Crystal ○ https://manas.tech/blog/2017/01/16/from-a-db-to-json-with-crystal/ ○ https://github.com/crystal-lang/crystal-db ● https://kemalcr.com/ ● https://amberframework.org/ ● https://luckyframework.org ● samples/2048.cr https://github.com/crystal-lang/crystal/tree/master/samples ● sdl raytracer https://github.com/asterite/crystal_sdl2_examples ● nes https://github.com/asterite/nes.cr Apps & Frameworks