Haskell程式:檢查三個布林變數中是否有兩個為真


本教程將討論如何編寫一個Haskell程式來檢查三個布林變數中是否有兩個為真。

布林變數是一種儲存布林值(真或假)的變數。

在本教程中,我們將學習兩種不同的方法來實現一個程式,以檢查三個布林值中是否有兩個為真。

  • 使用迭代方法檢查三個布林值中是否有兩個為真的程式。

  • 使用遞迴方法檢查三個布林值中是否有兩個為真的程式。

演算法步驟

  • 宣告或輸入三個布林值。

  • 實現程式以檢查三個布林變數中是否有兩個為真。

  • 列印或顯示狀態。

示例1

使用迭代方法檢查三個布林值中是否有兩個為真的程式

main = do -- declaring and initializing variables for interest parameters let a = True let b = True let c = False -- printing the status print ("Is the status of two boolean variables true?") if(a==True) then if( b==True) then print("yes") else if(c==True) then print("yes") else print("no") else if(b==True) then if(c==True) then print("yes") else print("no") else print ("no")

輸出

"Is the status of two boolean variables true?"
"yes"

在上面的程式中,我們宣告並初始化了三個變數a、b和c,並賦予它們隨機的布林值。

  • 程式檢查第一個變數a的值。

    • 如果第一個變數為真,則檢查第二個變數。

      • 如果第二個變數也為真,則程式列印“yes”,因為有兩個變數的值為真。

      • 否則,如果第二個變數為假,則程式檢查第三個變數。

        • 如果第三個變數為真,則程式列印“yes”,因為有兩個變數的值為真。

        • 否則,如果第三個變數為假,則程式列印“no”,因為只有一個變數的值為真。

    • 否則,如果第一個變數為假,則程式檢查第二個變數。

      • 如果第二個變數為真,則檢查第三個變數。

        • 如果第三個變數為真,則程式列印“yes”,因為有兩個變數的值為真。

        • 否則,如果第三個變數為假,則程式列印“no”,因為三個變數中只有兩個變數的值不為真。

      • 否則,如果第二個變數為假,則程式列印“no”,因為三個變數中只有兩個變數的值不為真。

示例2

使用遞迴方法檢查三個布林值中是否有兩個為真的程式

-- function declaration for function check check ::[Bool]->Int -- function definition for function check -- base case check [] = 0 check (x:xs) = if (x) then 1 + check xs else check xs main :: IO() main = do -- declaring and initializing variables for interest parameters let a = True let b = False let c = False -- computing the count of true values by invoking the function check let status = check [a,b,c] -- printing the status by evaluating the variable status print ("Is the status of two out of three boolean variables true?") if(status>=2) then print ("yes") else print ("no")

輸出

"Is the status of two out of three boolean variables true?"
"no"

在上面的程式中,我們聲明瞭一個名為`check`的函式,它接受一個布林值列表作為引數並返回一個整數。在函式定義中,我們使用模式匹配語法接受一個元素列表作為引數。該函式檢查第一個元素:如果第一個元素為真,則函式返回一個整數1加上對自身(使用剩餘列表作為引數)的遞迴呼叫。如果元素為假,則函式只返回對自身(使用剩餘列表作為引數)的遞迴呼叫。遞迴呼叫將一直進行,直到達到基本情況(列表為空),此時函式返回0。也就是說,函式返回列表中真值的個數。在主函式中,我們宣告並初始化了三個變數a、b和c的值。我們呼叫函式`check`,引數是一個包含這三個變數的列表,並將返回的計數載入到變數`status`中。如果`status`大於或等於2,我們列印“yes”;否則,我們列印“no”。

結論

在本教程中,我們討論了兩種不同的方法來實現一個Haskell程式,以檢查三個布林變數中是否有兩個為真。

更新於:2022年11月24日

瀏覽量:252

開啟你的職業生涯

透過完成課程獲得認證

開始學習
廣告