Tipos de datos · 2017-05-31 · y constantes Concepto de subtipo: un tipo de datos puede tener subtipos, ... declaraciones de datos en un ... Se identifican por un nombre y un rango
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Ojo: un tipo de datos no es un objeto de datos: • no ocupa espacio en memoria• es sólo una definición para usar más adelante al crear variables
y constantes
Concepto de subtipo: un tipo de datos puede tener subtipos, que restringen el rango o la precisión del tipo.• Los datos de diferentes tipos no se pueden mezclar. • Pero podemos mezclar datos de diferente subtipo si proceden
¿Cuándo usar tipos o subtipos?• usar subtipos para cosas de la misma naturaleza (p.e., sueldos)• usar tipos para cosas de naturaleza diferente (p.e., sueldo y
temperatura)
Subtipos enteros predefinidos:subtype Natural is Integer range 0..Integer’Last;subtype Positive is Integer range 1..Integer’Last;
Sus valores son identificadores. Evitan la necesidad de usar "códigos".
type Color is (Rojo, Verde, Azul);type Escuela is (Teleco, Caminos, Fisicas);
Los valores están ordenados, por el orden en que se escriben
Atributos más útiles de los tipos enumerados:Tipo’First primer valorTipo’Last último valorTipo’Succ(Valor) sucesor: siguiente a ValorTipo’Pred(Valor) predecesorTipo’Pos(Valor) código numérico del Valor (empiezan en cero)Tipo’Val(Número) Valor enumerado correspondiente al númeroTipo’Image(Valor) Conversión a textoTipo’Value(Texto) Conversión de texto a enumerado
Ada.Text_IO contiene submódulos genéricos: • los podemos especializar para leer o escribir datos de tipos
creados por nosotros
Poner en las declaraciones una (o varias) de estas líneas:package Int_IO is new Ada.Text_IO.Integer_IO(Mi_Tipo_Entero);package F_IO is new Ada.Text_IO.Float_IO(Mi_Tipo_Real);package Color_IO is new Ada.Text_IO.Enumeration_IO (Mi_Tipo_Enum);
Esto crea los módulos Int_IO, F_IO, y Color_IO• cada uno con operaciones Get y Put para leer o escribir,
respectivamente, datos de los tipos indicados.• tratamiento igual que con el resto de módulos (ej. cláusula use)
with Ada.Text_IO;use Ada;procedure Nota_Media_Enum is type Nota_num is range 0..10; type Nota_Letra is (Suspenso,Aprobado,Notable,Sobresaliente); package Nota_IO is new Text_IO.Integer_IO(Nota_Num); package Letra_IO is new Text_IO.Enumeration_IO(Nota_Letra); Nota1,Nota2,Nota3,Nota_Media : Nota_Num; Nota_Final : Nota_Letra;begin Text_IO.Put("Nota del primer trimestre: "); Nota_IO.Get(Nota1); Text_IO.Skip_Line; Text_IO.Put("Nota del segundo trimestre: "); Nota_IO.Get(Nota2);
Text_IO.Skip_Line; Text_IO.Put("Nota del tercer trimestre: "); Nota_IO.Get(Nota3); Text_IO.Skip_Line; Nota_Media := (Nota1+Nota2+Nota3)/3; Text_IO.Put("Nota Media : "); Nota_IO.Put(Nota_Media); Text_IO.New_Line; case Nota_Media is when 0..4 => Nota_Final:=Suspenso; when 5..6 => Nota_Final:=Aprobado; when 7..8 => Nota_Final:=Notable; when 9..10 => Nota_Final:=Sobresaliente; end case; Text_IO.Put("Nota Final : "); Letra_IO.Put(Nota_Final); Text_IO.New_Line;end Nota_Media_Enum;
type Meses is (Enero, Febrero, Marzo, Abril, Mayo, Junio, Julio, Agosto, Septiembre, Octubre, Noviembre, Diciembre);type Num_Dias_Mes is array (Integer range 1..12) of Natural;type Num_Dias is array (Meses) of Natural;
type Matriz is array (1..3,1..3) of Float;
subtype Hora is Integer range 0..23;subtype Temp is Float range -273.0..1000.0;type Tabla_Temperaturas is array (Hora,Meses) of Temp;
Los rangos no tienen por qué ser estáticos:N : Integer := valor;type Bool is array (1..N) of Boolean;
• Completo: por su nombre• Un elemento: nombre(indice)• Una parte: nombre(indice1..indice2)
Ejemplos: V1, V2 : Vector_3D M : Matriz Dias : Num_Dias; T : Tabla_Temperaturas; B : array (1..100) of Integer; -- Array de tipo anónimo Contactos : Bool; ... V1(1):=3.0+V2(3); V2:=V1; M(2,3):=M(1,1)*2.0; Dias(Enero):=31; T(20,Febrero):=23.1;
with Ada.Text_IO,Ada.Integer_Text_IO,Ada.Float_Text_IO;use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Float_Text_IO;
procedure Producto is Dimension_Max : constant Integer := 100; type Vector is array (1..Dimension_Max) of Float; V1,V2 : Vector; N : Integer range 1..Dimension_Max; Prod_Escalar : Float:=0.0;begin Put("Introduce dimension : "); Get(N); Skip_Line; Put_Line("Vector V1:"); for I in 1..N loop Put("Introduce componente "); Put(I); Put(": "); Get(V1(I)); Skip_Line; end loop;
with Ada.Text_Io,Ada.Integer_Text_Io,Ada.Float_Text_Io;use Ada.Text_Io, Ada.Integer_Text_Io, Ada.Float_Text_Io;
procedure Producto_Variable is N : Positive; Prod_Escalar : Float:=0.0;begin Put("Introduce dimension : "); Get(N); Skip_Line; declare type Vector is array (1..N) of Float; V1,V2 : Vector; begin Put_Line("Vector V1:"); for I in Vector’Range loop Put("Introduce componente "); Put(I); Put(": ");
Ejemplo versión 2: arrays de dimensión variable (cont.)
Get(V1(I)); Skip_Line; end loop; Put_Line("Vector V2:"); for I in V2’Range loop Put("Introduce componente "); Put(I); Put(": "); Get(V2(I)); Skip_Line; end loop;
for I in 1..N loop Prod_Escalar:=Prod_Escalar + V1(I)*V2(I); end loop; Put("El producto escalar es : "); Put(Prod_Escalar); New_Line; end;end Producto_Variable;
with Ada.Text_IO,Ada.Integer_Text_IO,Ada.Float_Text_IO;use Ada.Text_IO, Ada.Integer_Text_IO, Ada.Float_Text_IO;
procedure Producto_Irrestringido is type Vector is array (Positive range <>) of Float; N : Positive; Prod_Escalar : Float:=0.0;begin Put("Introduce dimension : "); Get(N); Skip_Line; declare V1,V2 : Vector(1..N); begin Put_Line("Vector V1:"); for I in V1’Range loop Put("Introduce componente "); Put(I); Put(": ");
Get(V1(I)); Skip_Line; end loop; Put_Line("Vector V2:"); for I in V2’Range loop Put("Introduce componente "); Put(I); Put(": "); Get(V2(I)); Skip_Line; end loop; for I in 1..N loop Prod_Escalar:=Prod_Escalar + V1(I)*V2(I); end loop; Put("El producto escalar es : "); Put(Prod_Escalar); New_Line; end;end Producto_Irrestringido;
Se identifican por el nombre del registro y unos campos
Declaración:type Tipo_Escuela is (Teleco, Ciencias, Caminos);
type Alumno is record nombre : String(1..20); n_nombre : Integer range 0..20; num_Telefono : String (1..9); Escuela : Tipo_Escuela := Teleco;end record;
Los campos pueden tener valor inicial • que será luego asignado a cada variable que se cree de ese tipo
Ventajas• evitan la duplicidad de código• son el primer pilar de la división del programa en partes
Pero no sirven para hacer módulos de programa independientes
Un módulo de programa independiente tiene• datos cuya vida es de un ámbito mayor que el del subprograma• operaciones para manejar esos datos, en forma de
Llamada a un procedimiento• Se escribe como una instrucción:
Nombre (parámetros_actuales);
• Cada parámetro actual se asigna a un parámetro formal- por orden:
Suma (3.0, A, B);- por nombre:
Suma (X =>3.0, Y=>A, Suma =>B);
• Deben respetar las reglas de compatibilidad de tipos• Los in son parámetros de sólo lectura• Los out e in out deben ser variables (lectura/escritura)
Ejemplo de manejo de arrays con un procedimiento (cont.)
procedure Lee_Vector ( N : in Indice; V : out Vector) is begin for I in 1..N loop Put("Introduce comp. "); Put(I); Put(": "); Get(V(I)); Skip_Line; end loop; end Lee_Vector;
procedure P1 is A,B : Integer; procedure P2 is D,E : Integer begin ... end P2; F,G : Integer; procedure P3 is H,I : Integer; procedure P4 is J,K,B : Integer; begin ... end P4; begin ... end P3; L,M : Integer;begin ...end P1;
[1] J. BARNES. "Programming in Ada 2005", first edition. Addison-Wesley,
2006.
[2] J. BARNES. "Programming In Ada 95", first edition. Addison-Wesley, 1995.
[3] S. Tucker Taft, Robert A. Duff, Randall L. Brukardt, Erhard Ploedereder, and Pascal Leroy (Eds.). “Ada 2005 Reference Manual. Language and Standard Libraries. International Standard ISO/IEC 8652:1995(E) with Technical Corrigendum 1 and Amendment 1”. LNCS 4348, Springer, 2006.
[4] Productos libres de AdaCore: https://libre.adacore.com/