2017-08-26 129 views
2

如何組合兩種不同類型的列表並遍歷Haskell中的結果?如何在haskell中結合兩種不同類型的列表

例如:

input: [1,2,3] ['A','B','C'], 
output: ["A1","A2","A3","B1","B2","B3","C1","C2","C3"]. 

我試圖使使用IntChar,就像一個例子:

combine :: Int -> Char -> String 
combine a b = show b ++ show a 

這是不行的,但是,因爲如果我使用此功能combine 3 'A',輸出將是"'A'3",而不是"A3"

回答

3

show :: Char -> String確實會放單引號括起來的字符:

*Main> show 'A' 
"'A'" 

但由於type String = [Char],我們可以使用:

combine :: Int -> Char -> String 
combine i c = c : show i 

所以在這裏我們構建一個字符列表與c作爲頭(第一個字符)和show i(表示整數)作爲尾部。

現在我們可以使用列表解析,使兩個列表的組合:

combine_list :: [Int] -> [Char] -> [String] 
combine_list is cs = [combine i c | c <- cs, i <- is] 

這就產生輸出:

*Main> combine_list [1,2,3] ['A','B','C'] 
["A1","A2","A3","B1","B2","B3","C1","C2","C3"] 
2

你可以做如下:

combiner :: [Char] -> [Int] -> [String] 
combiner cs xs = (:) <$> cs <*> (show <$> xs) 

*Main> combiner ['A','B','C'] [1,2,3] 
["A1","A2","A3","B1","B2","B3","C1","C2","C3"] 

這裏(:) <$> cs(其中<$>是綴fmap)將構建一個適用函子列表而show <$> xs就像map show xs產生["1","2","3"]<*>我們只是運用應用性列表["1","2","3"]導致["A1","A2","A3","B1","B2","B3","C1","C2","C3"]

相關問題