Paradigmas de Linguagens de Programação Paradigma Imperativo [Teoria de Tipos] Aula #5 (CopyLeft)2009 - Ismar Frango ismar@mackenzie.br
Sistema de tipos O que é um sistema de tipos? “ A type system is a  tractable syntactic method for proving the absence of  certain program behaviors  by classifying phrases according to the kinds of values they c ompute ” Detecção de erros Segurança Design Abstração Verificação Evolução Documentação “ Types are the leaven of programming, they make it digestible” Robin Milner
Em outras palavras... Um  sistema de tipos  é uma definição precisa das associações entre o tipo de uma variável, seus valores e as operações possíveis sobre esses valores Um  erro de tipo  é qualquer erro que surja porque uma operação é tentada sobre um tipo de dado para o qual ela não está definida. Quanto custa um erro de tipo? implementação teste manutenção $1 $10 $100 $472mi $
Como classificar um sistema de tipos? weak    strong dynamic static manifest implicit
Strong or weak? A tipagem é mutável (é possível mudar o tipo do valor associado a uma variável)? Como são gerenciados os erros de tipo? Sim Não Crash!   Detectados (em tempo de comp. ou exec.)
Strong or weak? struct A { char c; int i; }; struct B { float f; char c; }; int main(int argc, char* argv) { struct A a = {'c', 1024}; struct B* b = (struct B*)&a; printf("'%c' %d %f '%c'\n", a.c, a.i, b->f, b->c); } C 'c' 1024 149611321247666274304.000000 ' '
Strong or weak? class Silly: def __init__(self, data): self.data = data def __add__(self, other): return str(self.data) + str(other.data) def double(a): return a + a print double(1) print double('x') print double([1]) print double(Silly({'a':1})) print double({'a':1}) Python 2 xx [1, 1] {'a': 1}{'a': 1} Traceback (most recent call last):   File "test.py", line 14, in ?     print double({'a':1})   File "test.py", line 8, in double      return a + a TypeError: unsupported operand types for +: 'dict' and 'dict'
Strong or weak? var s : array [1..10] of character;  s := 'hello';  Pascal ERRO
“ Why Pascal is Not My Favorite Programming Language ” Brian  W. Kernighan http://www.lysator.liu.se/c/bwk-on-pascal.html   Tipagem (muito) forte vale a pena? “ Comparing C and Pascal is rather like comparing a Learjet to a Piper Cub - one is meant for getting something done while the other is meant for learning.”
Static or dynamic? Quem sabe o tipo de um elemento? Em que momento operações  unsafe  são rejeitadas? Usa reflexão? A variável O elemento Compile time  Runtime Pouco   Muito
Static or dynamic? int i = 1;  C#3.0 List<string> list = new List<string>();  var i = 1;  var list = new List<string>();  var != object != Variant  Type inference!
Static or dynamic? Customer c = GetCustomer(); var d = new { Name = c.Name, City = c.City }; Tipo anônimo public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers where n < 5 select n; Console.WriteLine(&quot;Numbers < 5:&quot;); foreach ( var x in lowNums ) { Console.WriteLine(x); } } C#3.0 C#3.0 (LINQ)
Manifest or implicit? Em sistemas de tipos  manifest (explicit) ,  toda  a informação deve ser providenciada pelo programador Em sistemas de tipos  implicit ,  o maior número possível  de informação deve ser inferida
Exercitando... n=5 print(type(n))  --number s=&quot;5&quot; print(type(s))  -- string soma=n+s print(soma)  -- 10 print(type(soma))  --number c = n ..s print(c)  -- string (55) print(type(c))  -- string Lua
Exercitando... function newCounter () { var i = 0 return function ()  {  // anonymous function i = i + 1 return i } } c1 = newCounter() alert(c1()) alert(c1()) alert(c1()) alert(c1()) alert(c1()) Javascript
Exercitando...   FUNCTION F(X) INTEGER F, X F = X+1 RETURN N = F(37) FORTRAN
Exercitando... #include <stdio.h> int main(void)  { unsigned char *c; float f = 10; for (c = (char *)&f; c < sizeof(float) + (char *)&f; c++) { printf(&quot;%u &quot;,  *c); } putchar('\n'); return 0; } 0 0 32 65 C ERRO:  comparison between distinct pointer types `unsigned char*' and `char*' lacks a cast
Exercitando... #include <iostream> using namespace std; struct A { void f() { cout << &quot;Class A&quot; << endl; } }; struct B : A { void f() { cout << &quot;Class B&quot; << endl; } }; struct C : A { void f() { cout << &quot;Class C&quot; << endl; } }; void f(A* arg) { B* bp = (B*)(arg); C* cp = (C*)(arg); bp->f(); cp->f(); arg->f(); }; int main() { A aobj; C cobj; A* ap = &cobj; A* ap2 = &aobj; f(ap); f(ap2); } C B C A B C A virtual C C C A A A dynamic_cast<B*> 

Paradigmas de Linguagens de Programacao - Aula #5

  • 1.
    Paradigmas de Linguagensde Programação Paradigma Imperativo [Teoria de Tipos] Aula #5 (CopyLeft)2009 - Ismar Frango ismar@mackenzie.br
  • 2.
    Sistema de tiposO que é um sistema de tipos? “ A type system is a tractable syntactic method for proving the absence of certain program behaviors by classifying phrases according to the kinds of values they c ompute ” Detecção de erros Segurança Design Abstração Verificação Evolução Documentação “ Types are the leaven of programming, they make it digestible” Robin Milner
  • 3.
    Em outras palavras...Um sistema de tipos é uma definição precisa das associações entre o tipo de uma variável, seus valores e as operações possíveis sobre esses valores Um erro de tipo é qualquer erro que surja porque uma operação é tentada sobre um tipo de dado para o qual ela não está definida. Quanto custa um erro de tipo? implementação teste manutenção $1 $10 $100 $472mi $
  • 4.
    Como classificar umsistema de tipos? weak strong dynamic static manifest implicit
  • 5.
    Strong or weak?A tipagem é mutável (é possível mudar o tipo do valor associado a uma variável)? Como são gerenciados os erros de tipo? Sim Não Crash! Detectados (em tempo de comp. ou exec.)
  • 6.
    Strong or weak?struct A { char c; int i; }; struct B { float f; char c; }; int main(int argc, char* argv) { struct A a = {'c', 1024}; struct B* b = (struct B*)&a; printf(&quot;'%c' %d %f '%c'\n&quot;, a.c, a.i, b->f, b->c); } C 'c' 1024 149611321247666274304.000000 ' '
  • 7.
    Strong or weak?class Silly: def __init__(self, data): self.data = data def __add__(self, other): return str(self.data) + str(other.data) def double(a): return a + a print double(1) print double('x') print double([1]) print double(Silly({'a':1})) print double({'a':1}) Python 2 xx [1, 1] {'a': 1}{'a': 1} Traceback (most recent call last):   File &quot;test.py&quot;, line 14, in ?     print double({'a':1})   File &quot;test.py&quot;, line 8, in double     return a + a TypeError: unsupported operand types for +: 'dict' and 'dict'
  • 8.
    Strong or weak?var s : array [1..10] of character; s := 'hello'; Pascal ERRO
  • 9.
    “ Why Pascalis Not My Favorite Programming Language ” Brian W. Kernighan http://www.lysator.liu.se/c/bwk-on-pascal.html Tipagem (muito) forte vale a pena? “ Comparing C and Pascal is rather like comparing a Learjet to a Piper Cub - one is meant for getting something done while the other is meant for learning.”
  • 10.
    Static or dynamic?Quem sabe o tipo de um elemento? Em que momento operações unsafe são rejeitadas? Usa reflexão? A variável O elemento Compile time Runtime Pouco Muito
  • 11.
    Static or dynamic?int i = 1; C#3.0 List<string> list = new List<string>(); var i = 1; var list = new List<string>(); var != object != Variant Type inference!
  • 12.
    Static or dynamic?Customer c = GetCustomer(); var d = new { Name = c.Name, City = c.City }; Tipo anônimo public void Linq1() { int[] numbers = { 5, 4, 1, 3, 9, 8, 6, 7, 2, 0 }; var lowNums = from n in numbers where n < 5 select n; Console.WriteLine(&quot;Numbers < 5:&quot;); foreach ( var x in lowNums ) { Console.WriteLine(x); } } C#3.0 C#3.0 (LINQ)
  • 13.
    Manifest or implicit?Em sistemas de tipos manifest (explicit) , toda a informação deve ser providenciada pelo programador Em sistemas de tipos implicit , o maior número possível de informação deve ser inferida
  • 14.
    Exercitando... n=5 print(type(n)) --number s=&quot;5&quot; print(type(s)) -- string soma=n+s print(soma) -- 10 print(type(soma)) --number c = n ..s print(c) -- string (55) print(type(c)) -- string Lua
  • 15.
    Exercitando... function newCounter() { var i = 0 return function () { // anonymous function i = i + 1 return i } } c1 = newCounter() alert(c1()) alert(c1()) alert(c1()) alert(c1()) alert(c1()) Javascript
  • 16.
    Exercitando... FUNCTION F(X) INTEGER F, X F = X+1 RETURN N = F(37) FORTRAN
  • 17.
    Exercitando... #include <stdio.h>int main(void) { unsigned char *c; float f = 10; for (c = (char *)&f; c < sizeof(float) + (char *)&f; c++) { printf(&quot;%u &quot;, *c); } putchar('\n'); return 0; } 0 0 32 65 C ERRO: comparison between distinct pointer types `unsigned char*' and `char*' lacks a cast
  • 18.
    Exercitando... #include <iostream>using namespace std; struct A { void f() { cout << &quot;Class A&quot; << endl; } }; struct B : A { void f() { cout << &quot;Class B&quot; << endl; } }; struct C : A { void f() { cout << &quot;Class C&quot; << endl; } }; void f(A* arg) { B* bp = (B*)(arg); C* cp = (C*)(arg); bp->f(); cp->f(); arg->f(); }; int main() { A aobj; C cobj; A* ap = &cobj; A* ap2 = &aobj; f(ap); f(ap2); } C B C A B C A virtual C C C A A A dynamic_cast<B*> 