Home > database >  changing return value for certain argument with guards
changing return value for certain argument with guards

Time:07-19

I am trying to code a Haskell function that returns the number of days in a month, given the month and year. Here is what I currently have:

days :: Int -> Int -> Int
days month year
  month 1 = 31
  if ily year then month 2 = 29
  else month 2 = 28

The ily function is returning a Bool after determining whether the year is a leap year or not.

I kind of understand why this doesn't work but I'm unsure how to achieve what I am trying to. I'm essentially asking if there is a way to use conditionals to change the return value of a certain argument (in this case 2, or February).

CodePudding user response:

Yes, you've just got the syntax a little confused I think.

days :: Int -> Int -> Int
days 1 _                = 31 -- January always has 31 days
days 2 year | ily year  = 29 -- February during a leap year
            | otherwise = 28 -- February otherwise
days 3 _                = 31 -- March always has 31 days
days 4 _                = 30 -- April always has 30 days
...

Pattern matching at the function level is done by repeating the function name, then the arguments, and filling in any arguments you want to match against. Guards are indicated by following the function pattern with a vertical bar and then a conditional.

  • Related