使用庫函式比較數字和字串的 Haskell 程式


在 Haskell 中,我們將使用庫函式(包括 compare、min 和 max 函式)以及 Eq 和 Ord 型別類來比較數字和字串。在第一個示例中,我們將使用 (compare num1 num2 和 compare str1 str2) 函式,在第二個示例中,我們將使用 (max num1 num2 和 min str1 str2) 函式。在第三個示例中,我們將使用 (num1 == num2) 函式以及 (num1 /= num2) 型別類。

演算法

  • 步驟 1 − 匯入 Data.Ord 庫,其中包含 compare 函式。

  • 步驟 2 − 程式執行將從 main 函式開始。main() 函式控制整個程式。它被寫成 main = do。然後,main 函式定義了兩個整數變數 num1 和 num2,以及兩個字串變數 str1 和 str2,並列印比較結果。

  • 步驟 3 − 初始化名為“num1”、“num2”、“str1”和“str2”的變數。它們將分別儲存要比較的數字和字串。

  • 步驟 4 − 呼叫 compare 函式後,使用 'print' 函式將比較結果列印到控制檯。

示例 1

在此示例中,我們將瞭解如何使用 compare 函式比較數字和字串。

import Data.Ord (compare)

main :: IO ()
main = do
      let num1 = 5
          num2 = 10
          str1 = "hello"
          str2 = "world"

      print (compare num1 num2) 
      print (compare str1 str2)

輸出

LT
LT

示例 2

在此示例中,我們將瞭解如何使用 min 和 max 函式比較數字和字串。

main :: IO ()
main = do
      let num1 = 5
          num2 = 10
          str1 = "hello"
          str2 = "world"

      print (max num1 num2)
      print (min str1 str2)

輸出

10
"hello"

示例 3

在此示例中,我們將瞭解如何使用 Eq 和 Ord 型別類比較數字和字串。

main :: IO ()
main = do
      let num1 = 5
          num2 = 10
          str1 = "hello"
          str2 = "world"

      print (num1 == num2)  
      print (num1 /= num2)
      print (str1 <= str2)  
      print (str1 >= str2)

輸出

False
True
True
False

結論

在 Haskell 中,要比較數字和字串,我們可以使用 compare、min 和 max 函式以及 Eq 和 Ord 型別類。

更新於: 2023年3月13日

1K+ 次瀏覽

開啟您的 職業生涯

透過完成課程獲得認證

開始學習
廣告