O Tipo e o
 Tempo
     Andrei de A. Formiga
Universidade Federal da Paraíba
Tipagem Estática vs.
     Dinâmica
Sobre
Sobre (2)

• Vale Tudo: Tipagem Estática vs. Dinâmica



• Um caminho do meio
Palestrante

• Graduação em Eng. Elétrica

• Experiência Profissional
  o SGBD

  o Jogos

  o Monitoramento e Controle
Palestrante (2)
• Mestrado e Doutorado
  o Linguagens de Programação

  o Proc. de Documentos, Rec. de Padrões


• Pesquisa
  o Linguagens

  o Comp. Paralela

  o Aprendizado de Máquina
Tipologia Básica
Tipos: o que são?
• Tipo é um conjunto de valores

• Valores pertencem a um ou mais tipos

• Variável V tem Tipo T: V só pode
  assumir valores do conjunto T
Fun calculus!
• Expressões:
  o fun x = E
  oF E



• Regras
  o (fun x = E1) E2  E1[x=E2]
Fun Calculus: Constantes
• Booleanos: true, false



• Inteiros: 0, 1, …



• Operações: +, -, *, /, …
Fun Calculus: Exemplos
• quad  fun x = x * x



• quad 5



• quad 5  (fun x = x * x) 5  5 * 5
Fun Calculus: Problemas
• quad true



• 5 + true



• 3 / 0
                ?
Tipos Simples
• Expressões
  o fun x: T = E
  oF E


• Regras de Tipos
  o E: T2, (fun x: T1 = E): T1T2
  o F: T1T2, E:T1, (F E): T2


• Regra de Avaliação (igual)
Exemplos
• quad  fun x: Int = x * x

• quad: IntInt

• true: Bool

• quad true: ?        Erro de tipo!
-Cálculo com tipos
                 simples9.2   The Typing Relation                                                                                              103


→ (typed)                                                                                                                  Based on λ (5-3)

Syntax
                                                         Evaluation                                                                    t     →t
 t   ::=                                       ter ms:
                                                                                  t   1       →t      1
           x                                var iable                                                                                  (E-App1)
           λx : T . t                    abstr action                    t   1    t   2       →t      1   t   2

           t t                           application                              t   2       →t      2
                                                                                                                                       (E-App2)
                                                                         v1 t         2       → v1 t          2
 v   ::=                                       values:
           λx : T . t              abstr action value     ( λ x : T11 . t        12 )         v2 → [ x                v2] t   12   (E-AppAbs)

                                                         Typing                                                                    Γ         t : T
T    ::=                                      types:
                                                                                  x: T ∈ Γ
           T→T                     type of functions                                                                                       (T-Va r )
                                                                                 Γ            x: T
Γ    ::=                                     contexts:
                                                                        Γ, x: T1                  t   2   : T2
           ∅                          em pty context                                                                                       (T-Abs)
                                                                   Γ     λ x: T1 . t              2   : T1 →T2
           Γ, x: T            ter m var iable binding

                                                          Γ    t   1   : T11 →T12                         Γ       t   2   : T11
                                                                                                                                           (T-App)
                                                                         Γ            t   1   t   2   : T12


Figur e 9-1: Pur e sim ply t y ped lam bda-calculus (λ →)
Mais Detalhes
• Types and
  Programming
  Languages



• Benjamin Pierce
Garantias

• Corretude
  o Type safety/soundness
  o “Well-typed programs can’t go wrong”




• Completude
Estático ou Dinâmico?
• Duas etapas de avaliação

• Tende p/ verificação estática

• Cálculo não prescreve momento de
  verificar
Estático e Dinâmico
Interpretação
                 Entrada




Programa      Interpretador




                 Saída
Compilação
                                   Entrada




Programa
                                  Programa
              Compilador
                                  Compilado




           Verificação estática     Saída
Compilação como
        Otimização

• Fazer parte da avaliação antes

• Incluindo verificações estáticas

• Avaliação Parcial (partial evaluation)
Confiabilidade

• Efeito colateral da compilação



• Tipos vs. testes:
  o Unit testing isn’t enough, you need static typing
  o http://bit.ly/RlqUzJ
Mais Estágios?

• Macros

• Aspectos

• Multi-Stage Programming
Verificação vs. Declaração
• Declarar os tipos ou não?
  o (declaração opcional)




• Verificar os tipos estatica ou
  dinamicamente?
Declaração/Estática

• C, C++, Java, etc.



• Visão geral da tipagem estática
Sem Declaração/Dinâmica

• Python, Ruby, JavaScript, etc



• Visão geral da tipagem dinâmica
Decl. Opcional/Estática

• ML, Haskell



• Variáveis locais: C#, Scala, etc
Decl. Opcional/Dinâmica

• Common Lisp, Julia, Dart



• Possibilidade de Verificação Estática
Sistemas de Tipos
   Mais e mais features
Limitações dos Tipos
          Simples
• Tipos compostos

• Containers

• Hierarquias de tipos
Registros / Classes

• Possibilidade de criar novos tipos


• type Point = { x: Int; y: Int }
Registros / Classes
                                     11.8     Recor ds                                                                                                       129


→ {}                                                                                                                                      Extends λ → (9-1)

New syntactic for m s
                                                                                                       t   1      →t    1
 t   ::= ...                                                    ter m s:                                                                                (E-Pr o j )
                          i ∈ 1..n
                                                                                             t 1. l               → t 1. l
          { l i =t    i              }                         r ecor d
          t.l                                              pr oj ection                                t          →t
                                                                                                            j           j
                                                                                         i ∈ 1..j −1
                                                                                                                                                         (E-Rc d )
                                                                             { l i =v i              , l j =t j , l k =t k k∈ j +1..n }
 v   ::= ...                                                    values:      → { l i =v i    i ∈ 1..j −1
                                                                                                         , l j =t j , l k =t k k∈ j +1..n }
                          i ∈ 1..n
          { l i =v i                 }                   r ecor d value
                                                                            New typing r ules                                                       Γ      t : T
 T ::= ...                                                      types:
                          i ∈ 1..n
                                                                                    f or each i                     Γ       t i : Ti
        { l i : Ti                   }               type of r ecor ds                                                                                  (T-Rc d )
                                                                               Γ    { l i =t       i
                                                                                                       i ∈ 1..n
                                                                                                                  } : { l i : Ti     i ∈ 1..n
                                                                                                                                                }

New evaluation r ules                                         t   →t                 Γ         t           : { l i : Ti i ∈ 1..n }
                                                                                                   1
                                                                                                                                                        (T-Pr o j )
         { l i =v i   i ∈ 1..n
                                 }.l     j   → vj        (E-Pr o j Rc d )                   Γ              t 1 . l j : Tj



Figur e 11-7: Recor ds
Polimorfismo Paramétrico
• Containers

• Ex.: pontos inteiros ou float

• type PointI = { x: Int; y: Int }

• type PointF = { x: Float; y: Float }
Polimorfismo Paramétrico

• Construtor com parâmetro de tipo



• type Point[T] = { x: T; y: T }
Tipos Recursivos

• Definir tipos em função deles mesmos



• Uma árvore é:
  o Uma árvore vazia; ou
  o Um nó com dois filhos que são árvores
Subtipos
• Relações hierárquicas entre tipos

• Geral/Específico

• Relaciondo à herança em OO

• A <: B
186                                                   Subtipos                                                                                        15    Subtyping


  → <:             Top                                                                                                                            Based on λ → (9-1 )

  Syntax                                                                                Subtyping                                                               S <: T
      t      ::=                                                             ter m s:
                   x                                                      var iable                               S <: S                                       (S-Refl )
                   λ x : T. t                                          abstr action
                                                                                                         S <: U                U <: T
                   t t                                                 application                                                                         (S-Tr a n s)
                                                                                                                  S <: T
      v      ::=                                                       values:
                                                                                                              S <: Top                                         (S-To p)
                   λ x : T. t                              abstr action value
                                                                                                     T1 <: S1                  S2 <: T2
      T ::=                                                             types:                                                                             (S-Ar r o w )
                                                                                                         S1 →S2 <: T1 →T2
                   Top                                        m axim um type
                   T→T                                      type of f unctions          Typing                                                             Γ     t : T
                                                                                                              x: T ∈ Γ
      Γ      ::=                                                     contexts:                                                                                 (T-Va r )
                                                                                                              Γ        x : T
                   ∅                                          em pty context
                   Γ, x : T                           ter m var iable binding                         Γ, x : T1            t   2   : T2
                                                                                                                                                               (T-Abs)
                                                                                                 Γ       λ x : T1 . t      2   : T1 →T2
  Evaluation                                                              t   →t         Γ   t       : T11 →T12                     Γ     t       : T11
                                                                                                 1                                            2
                                t        →t                                                                                                                    (T-App)
                                    1         1
                                                                           (E-App1)                      Γ     t   1   t   2   : T12
                       t    1   t   2    →t   1   t   2
                                                                                                     Γ       t : S                 S <: T
                                t   2    →t                                                                                                                    (T-Su b)
                                              2
                                                                          (E-App2)                            Γ        t : T
                       v1 t         2    → v1 t       2

          ( λ x : T11 . t   12 )        v2 → [ x          v2] t   12   (E-AppAbs)


  Fi gu r e 15-1: Si m pl y t y ped l am bda-cal cu l u s w i t h su bt y pi n g (λ <: )




                      15.2.2               Ex er c i se [ ]: Is t his t he only der ivat ion of t he st at em ent                                 f x y : Nat ?
Mais
• Phantom Types

• GADTs

• Higher-kinded Types

• Bounded quantification

• Tipos existenciais
Linguagens Atuais
• Haskell (+extensões)
  o   Polimorfismo paramétrico
  o   Phantom Types
  o   GADTs
  o   Higher-Kinded Types


• OCaml
  o Polimorfismo paramétrico
  o Phantom Types
  o GADTs
Linguagens Atuais
• Java
  o Polimorfismo paramétrico
  o Tipos existenciais (wildcards)


• Scala
  o   Polimorfismo paramétrico
  o   Higher-kinded types
  o   Anotações de variância
  o   GADTs
  o   etc…
Muito Complexo?
• Benjamin Pierce, “Types Considered Harmful”


• Luca Cardelli: “I was not the only one to
  suspect that I was getting lost in type theory”


• Erik Meijer, “Static Typing Where Possible,
  Dynamic Typing When Needed”
Tipos e Proposições
• Verificador de tipos é um provador de
  teoremas

• Tipagem 100% estática exige provar tipos
  em todo o código

• Tipagem 100% dinâmica joga fora
  informação útil
Sistemas Híbridos e
     Exemplos
Sistemas Híbridos

• Gradual Typing



• Blame calculus
Common Lisp

• Declaração opcional de tipos

• Objetivo: otimização

• Possível fazer verificações estáticas
Common Lisp
(iter (for el in number-list)
      (count (oddp el))))



(iter (for el in number-list)
      (declare (fixnum el))
      (count (oddp el))))
Typed Racket
• Declaração opcional de tipos



• Verificação estática quando possível



• Verificação dinâmica quando necessário
Typed Racket

#lang typed/racket
(: sum-list ((Listof Number) -> Number))
(define (sum-list l)
  (cond [(null? l) 0]
        [else (+ (car l) (sum-list (cdr l)))]))
Dart
• Declaração opcional de tipos (Dynamic)



• Objetivo: Documentação e verificações



• Tipagem dinâmica com verificações
  estáticas
Julia
• Declaração opcional + verif. Dinâmica



• Objetivo principal: Desempenho



• Possível para verificação estática
Perguntas?

• Twitter: @andreiformiga



• Blog: http://andreiformiga.com/blog

O Tipo e o Tempo

  • 1.
    O Tipo eo Tempo Andrei de A. Formiga Universidade Federal da Paraíba
  • 2.
  • 3.
  • 4.
    Sobre (2) • ValeTudo: Tipagem Estática vs. Dinâmica • Um caminho do meio
  • 5.
    Palestrante • Graduação emEng. Elétrica • Experiência Profissional o SGBD o Jogos o Monitoramento e Controle
  • 6.
    Palestrante (2) • Mestradoe Doutorado o Linguagens de Programação o Proc. de Documentos, Rec. de Padrões • Pesquisa o Linguagens o Comp. Paralela o Aprendizado de Máquina
  • 7.
  • 8.
    Tipos: o quesão? • Tipo é um conjunto de valores • Valores pertencem a um ou mais tipos • Variável V tem Tipo T: V só pode assumir valores do conjunto T
  • 9.
    Fun calculus! • Expressões: o fun x = E oF E • Regras o (fun x = E1) E2  E1[x=E2]
  • 10.
    Fun Calculus: Constantes •Booleanos: true, false • Inteiros: 0, 1, … • Operações: +, -, *, /, …
  • 11.
    Fun Calculus: Exemplos •quad  fun x = x * x • quad 5 • quad 5  (fun x = x * x) 5  5 * 5
  • 12.
    Fun Calculus: Problemas •quad true • 5 + true • 3 / 0 ?
  • 13.
    Tipos Simples • Expressões o fun x: T = E oF E • Regras de Tipos o E: T2, (fun x: T1 = E): T1T2 o F: T1T2, E:T1, (F E): T2 • Regra de Avaliação (igual)
  • 14.
    Exemplos • quad fun x: Int = x * x • quad: IntInt • true: Bool • quad true: ? Erro de tipo!
  • 15.
    -Cálculo com tipos simples9.2 The Typing Relation 103 → (typed) Based on λ (5-3) Syntax Evaluation t →t t ::= ter ms: t 1 →t 1 x var iable (E-App1) λx : T . t abstr action t 1 t 2 →t 1 t 2 t t application t 2 →t 2 (E-App2) v1 t 2 → v1 t 2 v ::= values: λx : T . t abstr action value ( λ x : T11 . t 12 ) v2 → [ x v2] t 12 (E-AppAbs) Typing Γ t : T T ::= types: x: T ∈ Γ T→T type of functions (T-Va r ) Γ x: T Γ ::= contexts: Γ, x: T1 t 2 : T2 ∅ em pty context (T-Abs) Γ λ x: T1 . t 2 : T1 →T2 Γ, x: T ter m var iable binding Γ t 1 : T11 →T12 Γ t 2 : T11 (T-App) Γ t 1 t 2 : T12 Figur e 9-1: Pur e sim ply t y ped lam bda-calculus (λ →)
  • 16.
    Mais Detalhes • Typesand Programming Languages • Benjamin Pierce
  • 17.
    Garantias • Corretude o Type safety/soundness o “Well-typed programs can’t go wrong” • Completude
  • 18.
    Estático ou Dinâmico? •Duas etapas de avaliação • Tende p/ verificação estática • Cálculo não prescreve momento de verificar
  • 19.
  • 20.
    Interpretação Entrada Programa Interpretador Saída
  • 21.
    Compilação Entrada Programa Programa Compilador Compilado Verificação estática Saída
  • 22.
    Compilação como Otimização • Fazer parte da avaliação antes • Incluindo verificações estáticas • Avaliação Parcial (partial evaluation)
  • 23.
    Confiabilidade • Efeito colateralda compilação • Tipos vs. testes: o Unit testing isn’t enough, you need static typing o http://bit.ly/RlqUzJ
  • 24.
    Mais Estágios? • Macros •Aspectos • Multi-Stage Programming
  • 25.
    Verificação vs. Declaração •Declarar os tipos ou não? o (declaração opcional) • Verificar os tipos estatica ou dinamicamente?
  • 26.
    Declaração/Estática • C, C++,Java, etc. • Visão geral da tipagem estática
  • 27.
    Sem Declaração/Dinâmica • Python,Ruby, JavaScript, etc • Visão geral da tipagem dinâmica
  • 28.
    Decl. Opcional/Estática • ML,Haskell • Variáveis locais: C#, Scala, etc
  • 29.
    Decl. Opcional/Dinâmica • CommonLisp, Julia, Dart • Possibilidade de Verificação Estática
  • 30.
    Sistemas de Tipos Mais e mais features
  • 31.
    Limitações dos Tipos Simples • Tipos compostos • Containers • Hierarquias de tipos
  • 32.
    Registros / Classes •Possibilidade de criar novos tipos • type Point = { x: Int; y: Int }
  • 33.
    Registros / Classes 11.8 Recor ds 129 → {} Extends λ → (9-1) New syntactic for m s t 1 →t 1 t ::= ... ter m s: (E-Pr o j ) i ∈ 1..n t 1. l → t 1. l { l i =t i } r ecor d t.l pr oj ection t →t j j i ∈ 1..j −1 (E-Rc d ) { l i =v i , l j =t j , l k =t k k∈ j +1..n } v ::= ... values: → { l i =v i i ∈ 1..j −1 , l j =t j , l k =t k k∈ j +1..n } i ∈ 1..n { l i =v i } r ecor d value New typing r ules Γ t : T T ::= ... types: i ∈ 1..n f or each i Γ t i : Ti { l i : Ti } type of r ecor ds (T-Rc d ) Γ { l i =t i i ∈ 1..n } : { l i : Ti i ∈ 1..n } New evaluation r ules t →t Γ t : { l i : Ti i ∈ 1..n } 1 (T-Pr o j ) { l i =v i i ∈ 1..n }.l j → vj (E-Pr o j Rc d ) Γ t 1 . l j : Tj Figur e 11-7: Recor ds
  • 34.
    Polimorfismo Paramétrico • Containers •Ex.: pontos inteiros ou float • type PointI = { x: Int; y: Int } • type PointF = { x: Float; y: Float }
  • 35.
    Polimorfismo Paramétrico • Construtorcom parâmetro de tipo • type Point[T] = { x: T; y: T }
  • 36.
    Tipos Recursivos • Definirtipos em função deles mesmos • Uma árvore é: o Uma árvore vazia; ou o Um nó com dois filhos que são árvores
  • 37.
    Subtipos • Relações hierárquicasentre tipos • Geral/Específico • Relaciondo à herança em OO • A <: B
  • 38.
    186 Subtipos 15 Subtyping → <: Top Based on λ → (9-1 ) Syntax Subtyping S <: T t ::= ter m s: x var iable S <: S (S-Refl ) λ x : T. t abstr action S <: U U <: T t t application (S-Tr a n s) S <: T v ::= values: S <: Top (S-To p) λ x : T. t abstr action value T1 <: S1 S2 <: T2 T ::= types: (S-Ar r o w ) S1 →S2 <: T1 →T2 Top m axim um type T→T type of f unctions Typing Γ t : T x: T ∈ Γ Γ ::= contexts: (T-Va r ) Γ x : T ∅ em pty context Γ, x : T ter m var iable binding Γ, x : T1 t 2 : T2 (T-Abs) Γ λ x : T1 . t 2 : T1 →T2 Evaluation t →t Γ t : T11 →T12 Γ t : T11 1 2 t →t (T-App) 1 1 (E-App1) Γ t 1 t 2 : T12 t 1 t 2 →t 1 t 2 Γ t : S S <: T t 2 →t (T-Su b) 2 (E-App2) Γ t : T v1 t 2 → v1 t 2 ( λ x : T11 . t 12 ) v2 → [ x v2] t 12 (E-AppAbs) Fi gu r e 15-1: Si m pl y t y ped l am bda-cal cu l u s w i t h su bt y pi n g (λ <: ) 15.2.2 Ex er c i se [ ]: Is t his t he only der ivat ion of t he st at em ent f x y : Nat ?
  • 39.
    Mais • Phantom Types •GADTs • Higher-kinded Types • Bounded quantification • Tipos existenciais
  • 40.
    Linguagens Atuais • Haskell(+extensões) o Polimorfismo paramétrico o Phantom Types o GADTs o Higher-Kinded Types • OCaml o Polimorfismo paramétrico o Phantom Types o GADTs
  • 41.
    Linguagens Atuais • Java o Polimorfismo paramétrico o Tipos existenciais (wildcards) • Scala o Polimorfismo paramétrico o Higher-kinded types o Anotações de variância o GADTs o etc…
  • 42.
    Muito Complexo? • BenjaminPierce, “Types Considered Harmful” • Luca Cardelli: “I was not the only one to suspect that I was getting lost in type theory” • Erik Meijer, “Static Typing Where Possible, Dynamic Typing When Needed”
  • 43.
    Tipos e Proposições •Verificador de tipos é um provador de teoremas • Tipagem 100% estática exige provar tipos em todo o código • Tipagem 100% dinâmica joga fora informação útil
  • 44.
  • 45.
    Sistemas Híbridos • GradualTyping • Blame calculus
  • 46.
    Common Lisp • Declaraçãoopcional de tipos • Objetivo: otimização • Possível fazer verificações estáticas
  • 47.
    Common Lisp (iter (forel in number-list) (count (oddp el)))) (iter (for el in number-list) (declare (fixnum el)) (count (oddp el))))
  • 48.
    Typed Racket • Declaraçãoopcional de tipos • Verificação estática quando possível • Verificação dinâmica quando necessário
  • 49.
    Typed Racket #lang typed/racket (:sum-list ((Listof Number) -> Number)) (define (sum-list l) (cond [(null? l) 0] [else (+ (car l) (sum-list (cdr l)))]))
  • 50.
    Dart • Declaração opcionalde tipos (Dynamic) • Objetivo: Documentação e verificações • Tipagem dinâmica com verificações estáticas
  • 51.
    Julia • Declaração opcional+ verif. Dinâmica • Objetivo principal: Desempenho • Possível para verificação estática
  • 52.
    Perguntas? • Twitter: @andreiformiga •Blog: http://andreiformiga.com/blog