[英]How to combine two different type of lists in haskell
How can I combine two different types of lists and traverse the result in Haskell? 如何合并两种不同类型的列表并遍历Haskell中的结果?
For example: 例如:
input: [1,2,3] ['A','B','C'],
output: ["A1","A2","A3","B1","B2","B3","C1","C2","C3"].
I tried making an example using Int
and Char
, like: 我尝试使用
Int
和Char
进行示例,例如:
combine :: Int -> Char -> String
combine a b = show b ++ show a
This doesn't work, however, because if I use this function for combine 3 'A'
, the output will be "'A'3"
, not "A3"
. 但是,这不起作用,因为如果我将此功能用于
combine 3 'A'
"'A'3"
combine 3 'A'
,则输出将为"'A'3"
,而不是"A3"
。
show :: Char -> String
will indeed put single quotes around the character: show :: Char -> String
实际上会将单引号引起来:
*Main> show 'A'
"'A'"
But since a type String = [Char]
, we can use: 但是由于
type String = [Char]
,我们可以使用:
combine :: Int -> Char -> String
combine i c = c : show i
So here we construct a list of characters with c
as the head (the first character), and show i
(the representation of the integer) as tail. 因此,在这里我们构造了一个以
c
为首(第一个字符)的字符列表,并以show i
(整数的表示形式)为尾。
Now we can use list comprehension to make a combination of two lists: 现在,我们可以使用列表推导来组合两个列表:
combine_list :: [Int] -> [Char] -> [String]
combine_list is cs = [combine i c | c <- cs, i <- is]
This then generates the output: 然后生成输出:
*Main> combine_list [1,2,3] ['A','B','C']
["A1","A2","A3","B1","B2","B3","C1","C2","C3"]
You may do as follows; 您可以执行以下操作;
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"]
Here (:) <$> cs
(where <$>
is infix fmap
) will construct an applicative list functor while show <$> xs
is like map show xs
yielding ["1","2","3"]
and by <*>
we just apply the applicative list to ["1","2","3"]
resulting ["A1","A2","A3","B1","B2","B3","C1","C2","C3"]
这里
(:) <$> cs
(其中<$>
是infix fmap
)将构造一个应用列表函子,而show <$> xs
就像map show xs
产生["1","2","3"]
并按<*>
我们仅将应用列表应用于["1","2","3"]
生成["A1","A2","A3","B1","B2","B3","C1","C2","C3"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.