Haskell 程式將布林變數轉換為字串
在 Haskell 中,我們將使用使用者定義函式 boolToString 以及 if-else 語句和模式匹配來將布林變數轉換為字串。在第一個示例中,我們將使用 (boolToString b = show b) 函式,在第二個示例中,我們將使用 (boolToString b = if b then "yes" else "no")。在第三個示例中,我們將使用模式匹配。
演算法
步驟 1 − 定義 boolToString 函式
步驟 2 − 程式執行將從 main 函式開始。main() 函式控制整個程式。它被寫成 main = do。
步驟 3 − 變數名為“boolVar”,正在初始化。它將儲存要轉換為相應字串值的布林型別變數。
步驟 4 − 呼叫函式 boolToString 並將 boolVar 傳遞給它。
步驟 5 − 函式呼叫後,使用 ‘putStrLn’ 語句將結果字串值列印到控制檯。
示例 1
在此示例中,定義了使用者定義函式 boolToString 以將布林變數轉換為字串。
boolToString :: Bool -> String boolToString b = show b main :: IO () main = do let boolVar = True let strVar = boolToString boolVar putStrLn $ "The boolean value is " ++ show boolVar ++ "." putStrLn $ "The corresponding string value is " ++ strVar ++ "."
輸出
The boolean value is True. The corresponding string value is True.
示例 2
在此示例中,使用 if-else 語句定義了使用者定義函式 boolToString 以將布林變數轉換為字串。
boolToString :: Bool -> String boolToString b = if b then "yes" else "no" main :: IO () main = do let boolVar = True let strVar = boolToString boolVar putStrLn $ "The boolean value is " ++ show boolVar ++ "." putStrLn $ "The corresponding string value is " ++ strVar ++ "."
輸出
The boolean value is True. The corresponding string value is yes.
示例 3
在此示例中,使用模式匹配定義了使用者定義函式 boolToString 以將布林變數轉換為字串。
boolToString :: Bool -> String boolToString True = "yes" boolToString False = "no" main :: IO () main = do let boolVar = True let strVar = boolToString boolVar putStrLn $ "The boolean value is " ++ show boolVar ++ "." putStrLn $ "The corresponding string value is " ++ strVar ++ "."
輸出
The boolean value is True. The corresponding string value is yes.
結論
布林值到字串的轉換是指將布林值(即 true 或 false)轉換為其對應的字串表示形式的過程。在大多數程式語言中,true 的字串表示形式通常為“true”或“True”,false 的字串表示形式通常為“false”或“False”。在 Haskell 中,布林變數使用使用者定義的 boolToString 函式以及 if-else 語句和模式匹配轉換為字串。
廣告