Haskell程式檢查兩個字串是否為迴文
在Haskell中,我們可以使用sort函式和freqMap來檢查給定的兩個字串是否為迴文。
什麼是迴文?
迴文是指透過重新排列另一個單詞或短語的字母而形成的單詞或短語,通常使用所有原始字母恰好一次。
例如,“listen”是“silent”的迴文。迴文常用於文字遊戲、謎題和其他娛樂形式。
演算法
步驟1 - 匯入Data.List模組以使用sort函式。
步驟2 - 定義使用sort函式的isAnagram函式
步驟3 - 程式執行將從main函式開始。main()函式控制整個程式。它寫成main = do。在main函式中,將兩個字串傳遞給isAnagram函式。函式的結果用於列印一條訊息,指示這兩個字串是否為迴文。
步驟4 - 變數“str1”和“str2”被初始化。它將儲存要檢查的字串,以確定它們是否為迴文。
步驟5 - 在呼叫函式後,使用‘putStrLn’語句將結果列印到控制檯。
示例1
在此示例中,isAnagram函式透過對字串進行排序並將排序後的字串進行相等性比較來檢查兩個字串是否彼此為迴文。Data.List庫中的sort函式用於對字串進行排序。
import Data.List isAnagram :: String -> String -> Bool isAnagram str1 str2 = sort str1 == sort str2 main :: IO () main = do let str1 = "listen" let str2 = "silent" if isAnagram str1 str2 then putStrLn "The two strings are anagrams of each other." else putStrLn "The two strings are not anagrams of each other."
輸出
The two strings are anagrams of each other.
示例2
在此示例中,isAnagram函式使用freqMap函式為兩個輸入字串建立頻率對映,並比較頻率對映的相等性。freqMap函式以字串作為輸入,並返回一個Map,表示字串中每個字元的頻率。Map.fromListWith函式用於透過建立表示每個字元及其頻率的元組列表來建立頻率對映,然後將列表與組合函式((+))一起傳遞給Map.fromListWith,該函式將多次出現的字元的頻率加起來。
import Data.List import Data.Map (Map) import qualified Data.Map as Map isAnagram :: String -> String -> Bool isAnagram str1 str2 = freqMap str1 == freqMap str2 where freqMap = Map.fromListWith (+) . map (\c -> (c, 1)) main :: IO () main = do let str1 = "listen" let str2 = "silent" if isAnagram str1 str2 then putStrLn "The two strings are anagrams of each other." else putStrLn "The two strings are not anagrams of each other."
輸出
The two strings are anagrams of each other.
示例3
在此示例中,isAnagram函式比較兩個輸入字串的字元計數。charCount函式以字串作為輸入,並返回一個數組,表示字串中每個字元的計數。accumArray函式用於透過建立表示每個字元及其計數的元組列表來建立字元計數陣列,然後將列表與初始值為零的組合函式((+))一起傳遞給accumArray,該函式將多次出現的字元的計數加起來。
import Data.Array isAnagram :: String -> String -> Bool isAnagram str1 str2 = str1CharCount == str2CharCount where str1CharCount = charCount str1 str2CharCount = charCount str2 charCount str = accumArray (+) 0 ('a', 'z') [(c, 1) | c <- str, c >= 'a' && c <= 'z'] main :: IO () main = do let str1 = "listen" let str2 = "silent" if isAnagram str1 str2 then putStrLn "The two strings are anagrams of each other." else putStrLn "The two strings are not anagrams of each other."
輸出
The two strings are anagrams of each other.
結論
在Haskell中,我們可以透過使用sort函式、頻率對映或字元計數來檢查兩個傳遞的字串是否為迴文。