Haskell程式:建立Case語句
在Haskell中,我們可以使用模式匹配、digitToInt、reads和使用者自定義函式來將字元型變數轉換為整數。在第一個示例中,我們將使用case語句進行模式匹配;在第二個示例中,我們將使用`(charToInt c = if isDigit c then Just (digitToInt c) else Nothing)`;在第三個示例中,我們將使用`(charToInt c = case reads [c] of [(x, "")] -> Just x and _ -> Nothing)`函式。
演算法
步驟1 - 定義內部函式
步驟2 - 程式執行將從main函式開始。main()函式控制整個程式的執行,其定義為`main = do`。
步驟3 - 初始化名為“digit”的變數,用於儲存要轉換為相應整數的字元。
步驟4 - 定義用於比較數字的case語句。
步驟5 - 函式呼叫後,使用`putStrLn`語句將結果整數列印到控制檯。
示例1
在這個例子中,函式使用使用者自定義的charToInt函式以及fromEnum函式來將字元型變數轉換為整數。
charToInt :: Char -> Int
charToInt c = fromEnum c - fromEnum '0'
main :: IO ()
main = do
let digit = '4'
case digit of
'0' -> putStrLn "The integer value is 0."
'1' -> putStrLn "The integer value is 1."
'2' -> putStrLn "The integer value is 2."
'3' -> putStrLn "The integer value is 3."
'4' -> putStrLn "The integer value is 4."
'5' -> putStrLn "The integer value is 5."
'6' -> putStrLn "The integer value is 6."
'7' -> putStrLn "The integer value is 7."
'8' -> putStrLn "The integer value is 8."
'9' -> putStrLn "The integer value is 9."
_ -> putStrLn "Invalid input. Please enter a digit character."
輸出
The integer value is 4.
示例2
在這個例子中,函式使用使用者自定義的charToInt函式以及digitToInt和isDigit函式來將字元型變數轉換為整數。
import Data.Char (digitToInt, isDigit)
charToInt :: Char -> Maybe Int
charToInt c = if isDigit c then Just (digitToInt c) else Nothing
main :: IO ()
main = do
let digit = '6'
case charToInt digit of
Just x -> putStrLn $ "The integer value is " ++ show x ++ "."
Nothing -> putStrLn "Invalid input. Please enter a digit character."
輸出
The integer value is 6.
示例3
在這個例子中,函式使用使用者自定義的charToInt函式以及reads函式來將字元型變數轉換為整數。
import Data.Char (digitToInt)
charToInt :: Char -> Maybe Int
charToInt c = case reads [c] of
[(x, "")] -> Just x
_ -> Nothing
main :: IO ()
main = do
let digit = '5'
case charToInt digit of
Just x -> putStrLn $ "The integer value is " ++ show x ++ "."
Nothing -> putStrLn "Invalid input. Please enter a digit character."
輸出
The integer value is 5.
結論
將char型變數轉換為int型變數通常涉及從其字元編碼中提取字元的整數值。這可以使用程式語言提供的內建函式來完成,或者透過實現自定義函式從字元編碼中提取整數值來完成。在Haskell中,可以使用使用者自定義函式以及模式匹配、digitToInt和reads函式將char型變數轉換為int型變數。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP