如何在haskell中组合两种不同类型的列表

时间:2017-08-26 17:28:49

标签: string list haskell combinations

如何组合两种不同类型的列表并在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"

2 个答案:

答案 0 :(得分: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"]

答案 1 :(得分:2)

您可以执行以下操作;

(:) <$> cs

此处<$>(其中fmap为中缀show <$> xs)将构建一个应用列表仿函数,而map show xs就像["1","2","3"]产生<*>并且["1","2","3"]我们只需将应用列表应用于["A1","A2","A3","B1","B2","B3","C1","C2","C3"]生成$.each( myObj, function( key, value ){ ... if( sthg... ){ myObj.somethingWentHorriblyWrong = true; return false; } }); if( myObj.somethingWentHorriblyWrong ){ // ... do something, not forgetting to go: delete myObj.somethingWentHorriblyWrong; }