paradigmas de linguagens de programacao - aula #5

Post on 25-May-2015

1.731 Views

Category:

Education

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

Paradigmas de Linguagens de Programacao - Aula #5 Prof. Ismar Frango

TRANSCRIPT

Paradigmas de Paradigmas de Linguagens de Linguagens de ProgramaçãoProgramação

Paradigma Imperativo [Teoria de Tipos]Aula #5

(CopyLeft)2009 - Ismar Frango ismar@mackenzie.br

Sistema de tiposSistema de tipos

O que é um sistema de tipos?

“A type system is a tractable syntacticmethod for proving

the absence of certain

program behaviors by classifying

phrasesaccording to the

kinds of values theycompute”

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...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 valoresUm 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 Como classificar um sistema de tipos?tipos?

weak strong

dynamic

staticman

ifest

implic

it

Strong or weak?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?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' 1024 149611321247666274304.000000 ' '

C

Strong or weak?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

2xx[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 + aTypeError: unsupported operand types for +: 'dict' and 'dict'

Strong or weak?Strong or weak?

var s : array [1..10] of character; s := 'hello';

Pascal

ERRO

“Why Pascal is Not My Favorite Programming Language”Brian W. Kernighanhttp://www.lysator.liu.se/c/bwk-on-pascal.html

Tipagem (muito) forte vale a pena?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?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?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?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("Numbers < 5:"); foreach (var x in lowNums) { Console.WriteLine(x); }}

C#3.0

C#3.0(LINQ)

Manifest or implicit?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...Exercitando...

n=5print(type(n)) --numbers="5"print(type(s)) -- stringsoma=n+sprint(soma) -- 10print(type(soma)) --numberc = n ..sprint(c) -- string (55)print(type(c)) -- string

Lua

Exercitando...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...Exercitando...

FUNCTION F(X) INTEGER F, X F = X+1 RETURN

N = F(37)

FORTRAN

Exercitando...Exercitando...

#include <stdio.h>int main(void) { unsigned char *c; float f = 10;

for (c = (char *)&f; c < sizeof(float) + (char *)&f; c++) { printf("%u ", *c); } putchar('\n');

return 0; }

0 0 32 65

C

ERRO: comparison between distinct pointer types `unsigned char*' and `char*' lacks a cast

Exercitando...Exercitando...#include <iostream>using namespace std; struct A {void f() { cout << "Class A" << endl; }}; struct B : A {void f() { cout << "Class B" << endl; }}; struct C : A {void f() { cout << "Class C" << 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

BCABCA

virtual

CCCAAA

dynamic_cast<B*>

top related