2015-11-03 111 views
1

我一直在尋找了一段時間了,並沒有發現我的問題的任何答案。 我試圖編寫一個函數,根據是否在一年內返回特定月份的日期。我以前已經定義了函數「lapyear」。我的問題是如何在另一個If條件中創建If條件?哈斯克爾多個條件組合

謝謝你很多關於你的答案:)

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 
+0

'如果那麼如果然後X1 X2其他別的x3'?或者你可能有興趣在的['MultiWayIf'(https://downloads.haskell.org/~ghc/7.6.1/docs/html/users_guide/syntax-extns.html#multi-way-if)擴展GHC。 – Bakuriu

+0

無論如何,代碼似乎是錯誤的。你有'mes == [01,03,..]'然後'mes == 02'。但是列表不太可能是'Num'實例,所以這可能會引發類型錯誤。 – Bakuriu

+0

我想程序首先檢查lapyear anyo的條件,取決於對去其他三個條件 – Felix

回答

2

你可能會喜歡的MultiWayIf擴展。

{-# LANGUAGE MultiWayIf #-} 

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

謝謝!我認爲這會起作用,但現在出現一個錯誤,提示「多路if-expressions需要MultiWayIf打開」。我如何導入multiwayif? – Felix

+0

它的工作現在,我只有通過對multiwayif:一套-XMultiWayIf再次感謝你 – Felix

+2

注意'{ - #語言MultiWayIf# - }'。如果將它放在文件的最頂端,則不需要命令行標誌。 – luqui

0

在普通的Haskell一些替代(不擴展):

鏈的 if then else
  • if lapyear anyo then 
        if or [...] then 31 
        else if mes == 02 then 29 
        else 30 
    else ... 
    
  • 使用let

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

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

我相信最後一種是最流行的。

+0

似乎是最簡單的方式,而無需導入任何東西。謝謝! – Felix