Introducción a ADA Prácticas de Algorítmica y Complejidad Índice n n n n n n n n n Aspectos generales Tipos Estructuras de control Subprogramas Paquetes Excepciones Tipos Compuestos Tipos acceso Entrada / Salida Aspectos generales -- Este es el aspecto de un programa en Ada. with text_IO; use text_IO; procedure Programa is package enteros is new Integer_IO (Integer); use enteros; i, j : integer; begin get ( i ); -- Esto es un comentario muy tonto. get ( j ); put ("El resultado de la suma es "); if (i + j) mod 2 = 0 then put ("par"); else put ("impar"); end if; end Programa; Aspectos generales n Comentarios. n n Identificadores. n n n -- Esto es un comentario y abarca hasta el final de la linea. Identificador ::= letra{[subrayado]letra_o_digito} letra_o_digito ::= letra | digito No se distingue entre letras mayúsculas y minúsculas. Aspectos generales n Literales numéricos n Tipos básicos: Integer, float. n Ej. Num_alumnos : Integer; Temperatura : Float; n n Enteros y reales pueden tener exponentes, pero en el caso de los enteros los exponentes no pueden ser negativos. n n Ej. 10.22E-12 12E2 Base del número. n Ej. 2#1010# 16#AF28# 4#32#E3 (32 x 43) Tipos Declaración de tipos type Color is (Rojo, Amarillo, Verde); C : Color := Verde; Q: constant Color := Verde; type Esquema is array (0..5) of Integer; Perfil : Esquema; ………………….. Perfil(0) := 105; Declaración de subtipos subtype Dia is Integer range 1..31; D : Dia; Tipos Tipos numéricos simples P: Integer; Q : Float; Cambio de tipo I: Integer := 3; F: Float := 5.6; …… I := Integer( F ) + I; F := F + Float( I ); Tipos Atributos A : array (1..10) of character; type Color is (Rojo, Amarillo, Verde); integer’first Menor entero Color’last Verde integer’last Mayor entero Color’pred (Amarillo) Rojo A’first 1 Color’succ (Amarillo) Verde A’last 10 integer’value (“345”) Número 345 A’range 1..10 integer’image (345) String “345” subtype Natural is Integer range 0..Integer’Last; subtype Positive is Integer range 1..Integer’Last; Tipos n Tipos predefinidos n Boolean n Character n Integer n Natural n Positive n Float n String Operadores escalares Operador Operación Operando(s) Resultado And Or xor Y lógico O inclusivo O exclusivo Booleanos Booleanos Booleanos Booleano Booleano Booleano = /= < <= > >= Igualdad Desigualdad Menor que Menor o igual que Mayor que Mayor o igual que Cualquiera Cualquiera Escalar Escalar Escalar Escalar Booleano Booleano Booleano Booleano Booleano Booleano + - Adición Substracción Numérico Numérico Igual Igual + - Identidad Negación Numérico Numérico Igual Igual * / Mod Rem Multiplicación División Módulo Resto Integer o Float Integer o Float Integer Integer Integer o Float Integer o Float Integer Integer ** Exponenciación Not Negación Integer, Natural o Float, Integer Booleano Integer Float Booleano Abs Valor absoluto Numérico Igual Estructuras de control if Comando = Izquierda then Girar_Izquierda; elsif Comando = Derecha then Girar_Derecha; elsif Comando = Acelerar then Incrementar_Velocidad; elsif Comando = Decelerar then Decrementar_Velocidad; else Mantener_Velocidad; end if; Estructuras de control case Comando is when Izquierda => Girar_Izquierda; when Derecha => Girar_Derecha; when Acelerar => Incrementar_Velocidad; when Decelerar => Decrementar_Velocidad; when others => Mantener_Velocidad; end case; Estructuras de control loop loop Coge_tenedores; if Hora_Dormir then exit; Come; Medita; end loop; end if; Coge_tenedores; Come; Medita; end loop; Estructuras de control loop exit when Hora_Dormir; Coge_tenedores; Come; Medita; end loop; Estructuras de control while not Hora_Dormir loop for x in 1..3 loop Coge_tenedores; Medita; Come; Coge_tenedores; Medita; Come; end loop; end loop; for x in reverse 0..10 loop Di_Numero( x ); end loop; Subprogramas n Subprograma ::= procedure nombre parámetros | function nombre parámetros resultado n parámetros ::= (especificación{; especificación}) n especificación ::= lista_identificadores: modo subtipo n modo ::= [in | in out | out] n resultado ::= return subtipo Subprogramas function factorial( N: Positive) return Positive is begin if N = 1 then return 1; else return N * factorial( N – 1 ); end if; end factorial; procedure Add (A, B : in integer; C: out integer) is begin C := A+B; end Add; Subprogramas procedure Hacer_Algo ( A : integer; B : integer := 0; C : integer := 1 ) is begin ........ ........ end Hacer_Algo; Hacer_Algo ( 5, 4, 8 ); Hacer_Algo ( 7 ); Hacer_Algo ( 7, 0, 1 ); Hacer_Algo ( 9, C => 4 ); Hacer_Algo ( 9, 0, 4 ); Hacer_Algo (C => 4, A => 2, B => 7 ); Hacer_Algo (2, 7, 4 ); Paquetes package Pila_enteros is procedure Push( x: in Integer ); function Pop return Integer; end Pila_enteros; package body Pila_enteros is Max: constant := 100; S: array(1..Max) of Integer; Cima: Integer range 0..Max; procedure Push( x: Integer) is begin Cima := Cima + 1; S(Cima) := x; end Push; function Pop return Integer is begin Cima := Cima -1; return S(Cima+1); end Pop; begin Cima := 0; end Pila_enteros; Unidades de compilación n Cada procedimiento o paquete debe editarse en ficheros diferentes n Los procedimientos han de colocarse en ficheros de extensión “.adb” n La especificación de un paquete y el cuerpo (body) deben codificarse en ficheros diferentes: n Especificación extensión del fichero “.ads” n Cuerpo (body) extensión del fichero “.adb” n Para poder utilizar procedimientos o paquetes es necesario utilizar la sentencia with Excepciones n Permiten tratar situaciones poco frecuentes, pudiendo controlar con ellas un error del SW. n Predefinidas (las más habituales) n Constraint_Error n Program_Error n Storage_Error n Tasking_Error Ámbito de la excepción Excepciones begin …………. ………..... exception when Constraint_Error => -- Tratamiento especifico end; Manejador de la excepción Excepciones package Pila_enteros is ErrorPila: exception; procedure Push( x: in integer ); function Pop return integer; end Pila_enteros; Package body Pila_enteros is ………. ………. procedure Push( x: integer) is begin if Cima = Max then raise ErrorPila; end if; Cima := Cima + 1; S(Cima) := x; end Push; ………. ………. end Pila_enteros; Excepciones with Pila_enteros; procedure Actuar is begin ………. ………. Pila_enteros.Push(5); ………. ………. exception when ErrorPila => put(“Error en la pila”); end Actuar; Tipos Compuestos n Registros (record) type NOMBRE_MES is (ENE, FEB, MAR, ABR, MAY, JUN, JUL, AGO, SEP, OCT, NOV, DIC) type FECHA is record DIA: Integer range 1..31; MES: NOMBRE_MES; AÑO: Integer; end record; -- Declaración de variables F: FECHA; Tipos Compuestos -- Asignación F.DIA := 6; F.MES := SEP; F.AÑO := 2012; -- Otra forma de asignar F := (6, SEP, 2012); -- Una más F := (MES => SEP, AÑO => 2012, DIA => 6); Tipos Compuestos type COMPLEJO is record PR: Real := 0.0; PI: Real := 0.0; end record; -- Constantes I: constant COMPLEJO := (0.0, 1.0); -- Arrays NmrComplejos: array (1..10) of COMPLEJO; -- Asignaciones NmrComplejos (5).PR := 7.0; NmrComplejos (5).PI := 3.0; Tipos Acceso Referencias, variables dinámicas type CELDA; type ENLACE is access CELDA; type CELDA is record Valor: Integer; Siguiente: ENLACE end record; n Tipos Acceso -- Declaración E, F: ENLACE := null; -- Asignación E := new CELDA; E := new CELDA (137, null); F := new CELDA (138, E); F.Valor := E.Valor; F.Siguiente := F.Siguiente; F.all := E.all; Tipos Acceso procedure Insertar (Lista: in out ENLACE; V: in INTEGER) is begin Lista := new CELDA (V, Lista); end Insertar; -E: ENLACE := null; Insertar (E, 1); Insertar (E, 2); E 2 1 null Entrada / salida El paquete Text_IO proporciona herramientas para el manejo de la E/S de texto. Text_IO procedure...... procedure...... procedure...... function......... Integer_IO Float_IO Fixed_IO Decimal_IO Enumeration_IO Modular_IO Paquetes genéricos Entrada / salida Invocación de Text_IO Invocación de paquetes genéricos with Text_IO; use Text_IO; with Text_IO; use Text_IO; procedure prueba is ...... begin ...... end prueba; procedure prueba is ...... package enteros is new Integer_IO (Integer); use enteros; ...... begin ...... end prueba; Entrada / salida Caracteres procedure Get ( Item : out Character ); procedure Get ( File Item : in File_Type; : out Character ); procedure Put ( Item : in Character ); procedure Put ( File Item : in : in File_Type; Character ); procedure New_Line ( Spacing : in Positive_Count := 1); procedure New_Line ( File : in File_Type; Spacing : in Positive_Count := 1); Entrada / salida Cadenas de caracteres ( I ) procedure Get ( Item : out String ); procedure Get ( File Item : in File_Type; : out String ); procedure Put ( Item : in String ); procedure Put ( File Item : in : in File_Type; String ); Entrada / salida Cadenas de caracteres ( II ) procedure Get_Line ( Item Last : out String; : out Natural ); procedure Get_Line ( File Item Last : in File_Type; : out String; : out Natural ); procedure Put_Line ( Item : in String ); procedure Put_Line ( File Item : in : in File_Type; String ); Entrada / salida Números enteros procedure Get ( Item : out Num; Width : in Field := 0 ); procedure Get ( File : in File_Type; Item : out Num; Width : in Field := 0 ); procedure Put ( Item : in Width : in Base : in Num; Field := Default_Width; Number_Base := Default_Base ); procedure Put ( File Item Width Base File_Type; Num; Field := Default_Width; Number_Base := Default_Base ); : : : : in in in in Entrada / salida Números reales procedure Get ( Item : out Num; Width : in Field := 0 ); procedure Get ( File : in File_Type; Item : out Num; Width : in Field := 0 ); procedure Put ( Item Fore Aft Exp : : : : in in in in Num; Field := Default_Fore; Field := Default_Aft; Field := Default_Exp ); procedure Put ( File Item Fore Aft Exp : : : : : in in in in in File_Type; Num; Field := Default_Fore; Field := Default_Aft; Field := Default_Exp ); Entrada / salida Ficheros type File_Type is limited private; Type File_Mode is ( In_File, Out_File, Append_File ); procedure Create ( File Mode Name Form : : : : in out in in in File_Type; File_Mode String String procedure Open ( File Mode Name Form : : : : in out in in in File_Type; File_Mode; String; String := "" ); procedure Close ( File : in out File_Type ); procedure Delete ( File : in out File_Type ); function End_Of_File ( File : in out File_Type ); := Out_File; := ""; := "" ); Entrada / salida Ejemplo 1 with text_IO; use text_IO; procedure ejemplo is c : Character; begin Get (c); -- Lectura del carácter. if c=’a’ then Put (“Es la letra a.”); -- Si es la letra “a” lo decimos. end if; end ejemplo; Entrada / salida Ejemplo 2 with Text_IO; procedure Otro_Ejemplo is Fichero : Text_IO.File_Type; begin Text_IO.Create (Fichero, Text_IO.Out_File, "saludo.txt"); Text_IO.Put_Line (Fichero, "Este es un ejemplo de escritura"); Text_IO.Put_Line (Fichero, "en un fichero desde un “); Text_IO.Put_Line (Fichero, “programa Ada."); Text_IO.Close (Fichero); end Otro_Ejemplo; Entrada / salida Ejemplo 3 with Text_IO; procedure Otro_Ejemplo_2 is Fichero : Text_IO.File_Type; Linea : String (1 .. 80); Longitud : Natural; begin Text_IO.Open (Fichero, Text_IO.Out_File, "saludo.txt"); while not Text_IO.End_Of_File (Fichero) loop Text_IO.Get_Line (Fichero, Linea, Longitud); Text_IO.Put_Line (Linea (1 .. Longitud)); end loop; Text_IO.Close (Fichero); end Otro_Ejemplo_2; Bibliografía n Programming in ADA 95. John Barnes. Addison-Wesley. n Programming in ADA 2005. John Barnes. Addison-Wesley. n Curso Práctico de Programación. Usando Ada como primer lenguaje. F. J. Ballesteros.