简体   繁体   中英

Haskell multiple conditions combined

I've been looking for a while now and didn't find any answers to my question. I tried to write a function that returns the days of a specific month depending on whether it is in a lap year or not. I already defined the function "lapyear" previously. My question is how can I create an If condition within another If condition ?

Thank you a lot for your answers :)

lapyear:: Int->Bool
lapyear a
    |((rem)a 400)==0 = True
    |((rem)a 100)==0 = False
    |((rem)a 4)==0 = True
    |otherwise = False

type Mes = Int
type Anyo = Int
type Dias= Int
daysAmonth:: Mes->Anyo->Dias
daysAmonth mes anyo
if lapyear anyo then do
    |or[mes==01,mes==03,mes==05,mes==07,mes==08,mes==10,mes==12] = 31
    |mes==02 = 29
    |otherwise = 30
else
    |or[mes==01,mes==03,mes==05,mes==07,mes==08,mes==10,mes==12] = 31
    |mes==02 = 28
    |otherwise = 30

You might like the MultiWayIf extension.

{-# LANGUAGE MultiWayIf #-}

if lapyear anyo then if
    | or [...] -> 31
    | mes == 20 -> 29
    | otherwise -> 30
else if
    | ...

Some alternatives in plain Haskell (without extensions):

  • chain of if then else :

     if lapyear anyo then if or [...] then 31 else if mes == 02 then 29 else 30 else ... 
  • using let :

     if lapyear anyo then let result | or [...] = 31 | mes == 02 = 29 | otherwise = 30 in result else ... 
  • using case :

     if lapyear anyo then case () of _ | or [...] -> 31 | mes == 02 -> 29 | otherwise -> 30 else ... 

I believe the last one is the most popular.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM