Haskell程式:檢查字母是母音還是子音
我們可以使用Haskell中的`elem`函式來檢查給定的字母是母音還是子音。在第一個例子中,我們將使用`(isVowel c = c `elem` "aeiouAEIOU")`函式。在其他例子中,我們將結合使用`elem`函式和一些if-else語句、巢狀條件和守衛。
演算法
步驟1 - 定義資料型別’Person’,包含兩個欄位:姓名和年齡。
步驟2 - 使用`elem`函式定義`isVowel`函式:
步驟3 - 程式執行將從`main`函式開始。`main()`函式控制整個程式。它寫成`main = do`。
步驟4 - 使用if-else條件檢查變數是母音還是子音。然後將結果顯示到控制檯。
示例1
在這個例子中,使用`elem`函式檢查字母是母音還是子音。
isVowel :: Char -> Bool isVowel c = c `elem` "aeiouAEIOU" main :: IO () main = do let alphabet = 'a' if isVowel alphabet then putStrLn $ alphabet : " is a vowel" else putStrLn $ alphabet : " is a consonant"
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... a is a vowel
示例2
在這個例子中,我們定義了一個函式`isVowel`,它接受一個字元作為輸入,如果它是母音則返回`True`,否則返回`False`。然後,在`main`函式中,我們提示使用者輸入一個字元,並檢查它是否是一個有效的字母。如果是,我們使用`isVowel`函式檢查它是母音還是子音,並列印相應的提示資訊。如果輸入無效,我們列印錯誤資訊。
isVowel :: Char -> Bool isVowel c = c `elem` "aeiouAEIOU" main :: IO () main = do let alphabets ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" let c = 'a' if c `elem` alphabets then if isVowel c then putStrLn $ c : " is a vowel." else putStrLn $ c : " is a consonant." else putStrLn "Invalid input."
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... a is a vowel.
示例3
在這個例子中,函式`isVowel`接收一個字元作為輸入,如果字元是母音(a、e、i、o、u、A、E、I、O、U),則返回`True`,否則返回`False`。`elem`函式用於檢查字元是否在母音列表中。
isVowel :: Char -> Bool isVowel c = c `elem` "aeiouAEIOU" main :: IO () main = do let c1 = 'a' c2 = 'b' putStrLn $ "Is " ++ [c1] ++ " a vowel? " ++ show (isVowel c1) putStrLn $ "Is " ++ [c2] ++ " a vowel? " ++ show (isVowel c2)
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... Is a a vowel? True Is b a vowel? False
示例4
在這個例子中,定義了一個函式`isVowel`,它接受一個字元作為輸入,如果它是母音則返回`True`,否則返回`False`。`elem`函式用於檢查字元是否在字串"aeiouAEIOU"中,該字串包含所有母音。
isVowel :: Char -> Bool isVowel c = c `elem` "aeiouAEIOU" main :: IO () main = do let char1 = 'a' char2 = 'b' putStrLn $ char1 : if isVowel char1 then " is a vowel." else " is a consonant." putStrLn $ char2 : if isVowel char2 then " is a vowel." else " is a consonant."
輸出
[1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... a is a vowel. b is a consonant.
示例5
在這個例子中,定義了一個函式`isVowel`,如果給定的字元是母音,則返回`True`,否則返回`False`。然後,`main`函式生成字母表,並使用`isVowel`過濾它以分離母音和子音。最後,它列印這兩個列表。
isVowel :: Char -> Bool isVowel c | c `elem` "aeiouAEIOU" = True | otherwise = False main :: IO () main = do let alphabet = "abcdefghijklmnopqrstuvwxyz" putStrLn "Vowels: " putStrLn [ c | c <- alphabet, isVowel c ] putStrLn "
Consonants: " putStrLn [ c | c <- alphabet, not (isVowel c) ]
輸出
Vowels: [1 of 1] Compiling Main ( main.hs, main.o ) Linking main ... Vowels: aeiou Consonants: bcdfghjklmnpqrstvwxyz
結論
在英語中,母音是字母'a'、'e'、'i'、'o'、'u',有時還有'y'。子音是字母表中的所有其他字母。我們可以透過在Haskell中使用模式匹配和母音列表來檢查字母是母音還是子音。我們還可以結合使用`elem`函式和各種if-else條件。