2012-01-28 8 views
7

Ho appena imparato a conoscere Enums e tipi di Ada e ha deciso di scrivere un piccolo programma per la pratica:Come si può verificare se un elemento appartiene a un sottotipo o all'altro?

with Ada.Text_IO;      use Ada.Text_IO; 
with Ada.Integer_Text_IO;  use Ada.Integer_Text_IO; 

procedure Day is 

    type Day_Of_The_Week is (Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday); 

    subtype Weekday is Day_Of_The_Week range Monday..Friday; 

    subtype Weekend is Day_Of_The_Week range Saturday..Sunday; 

     function is_Weekday (dayOfTheWeek: in Day_Of_The_Week) return Boolean is 
     begin 
      if(--?--) 
     end is_Weekday; 

    selected_day_value : Integer; 
    selected_day    : Day_Of_The_Week; 

begin 
    Put_Line("Enter the number co-responding to the desired day of the week:"); 
    Put_Line("0 - Monday"); 
    Put_Line("1 - Tuesday"); 
    Put_Line("2 - Wednesday"); 
    Put_Line("3 - Thursday"); 
    Put_Line("4 - Friday"); 
    Put_Line("5 - Saturday"); 
    Put_Line("6 - Sunday"); 
    Get(selected_day_value); 
    selected_day = Day_Of_The_Week'pos(selected_day_value); 

    if(is_Weekday(selected_day)) 
     Put_Line(Day_Of_The_Week'Image(selected_day) & " is a weekday."); 
    else 
     Put_Line(Day_Of_The_Week'Image(selected_day) & " is a weekday."); 

end Day; 

Ho problemi con l'istruzione if. Come posso verificare se dayOfTheWeek è o meno nel sottotipo Weekday o nel sottotipo Weekend?

+0

Essere un pedante, ma il codice presuppone un input valido. IRL dovresti usare una clausola di rappresentazione sul tuo enum per garantire l'intervallo da 0 a 6, e ottenere un numero intero, usare una conversione non controllata al tuo tipo intero, controllare che sia valida, e quindi controllare i sottotipi fine settimana/giorno della settimana. – NWS

+0

Perché non inserire esplicitamente un 'Day_Of_The_Week'? 'pacchetto Day_Of_The_Week_Text_IO è nuovo Ada.Text_IO.Enumeration_IO (Day_Of_The_Week);' e quindi 'Get (Selected_Day); Skip_Line; ' –

risposta

8

Volete

function is_Weekday (dayOfTheWeek: in Day_Of_The_Week) return Boolean is 
begin 
    return dayoFTheWeek in Weekday; 
end is_Weekday; 

Inoltre, si vuole ’Val non ’Pos in

selected_day := Day_Of_The_Week'val(selected_day_value); 

e si potrebbe dare un'occhiata alle parole del secondo Put_Line!

2

Non è necessaria una funzione per verificare ciò. In questo caso, una funzione oscura solo ciò che accade:

if Selected_Day in Weekday then 
    do stuff.. 
else 
    do other stuff... 
end if; 
Problemi correlati