0
votes

I am learning Ocaml and as part of an exercise, I have to create a function that returns the following day of a couple (day, month, year).

I did the function, but the software that evaluates my code tells me I'm using too much if ... then ... else ... I haven't found a solution for several hours. Can someone help me ?

let leap = fun x -> x mod 4 = 0 && x mod 100 <> 0 || x mod 400 = 0

let nbDay(month,year) = match monthwith 
  | 1 | 3 | 5 | 7 | 8 | 10 | 12 -> 31
  | 4 | 6 | 9 | 11 -> 30
  | 2 -> if(leap(year)) then 29 else 28 
  | _ -> 0

let valid (day, month, year) = day <= nbDay(month,year) 
                               && day>= 1
                               && month<=12 
                               && month>= 1 


let tomorrow (day, month, year) = if(valid (day, month, year)) 
  then if(day= nbDay(month,year)) 
    then
      if(month= 12) 
      then 
        let day= 1 in 
        let month= 1 in 
        let year= year+ 1 in 
        (day, month, year)
      else 
        let day= 1 in 
        let month= month+ 1 in 
        (day, month, year)
    else 
      let day= day+ 1 in  
      (day, month, year)      
  else  failwith "invalid date!"
1
It is hard to answer your question without knowing more about your homework (for which SO isn't really fitted). Do you have a teacher to ask things to? - PatJ
my 2 cents : use exception instead of the first if/then/else, may be elsewhere also ; use also modulo and division... - Pierre G.

1 Answers

0
votes

You shall use match more, for example, instead of writing

if month = 12 then xxx ...

you can write

match month with
| 12 -> xxx
...

When your condition is more complex, you can use when, e.g., instead of writing

| 2 -> if is_leap year then x else y

you can write

| 2 when is_leap year -> x
| 2 -> y