map2_List :: (a -> b -> c) -> [a] -> [b] -> [c]
map2_List f [] _ = []
map2_List f (a:as) bs = map (f a) bs ++ map2_List f as bs
这是将二进制函数应用于两个列表的所有成对元素的示例。我感到困惑,为什么将每个(f a)
应用于bs
而不是分别将f
应用于[a]
和[b]
的每个元素。
有人可以举一个例子吗?
答案 0 :(得分:1)
您永远不会解构 foreach($seat_ids as $seat_id ){
foreach($seat_labels as $seat_label ){
$record = array(
'seatNumber' => $seat_id,
'seatLabel' => $seat_label,
'bookingDate' => $bookingDate,
'reportingTime' => $reportingTime,
'departureTime' => $departureTime,
'busNumber' => $busNumber,
'seatUse' => 'Enabled',
'seatStatus' => 'Available',);
$this->db->insert('schedule', $record);
}
}
列表,因此每次调用b
时,该列表将应用于map (f a)
的 each 值。例如,
bs
更紧凑的定义是将map2_List (+) [1,2,3] [10,11,12] == map (+ 1) [10,11,12] ++
map2_list (+) [2,3] [10,11,12]
== map (+ 1) [10,11,12] ++
map (+ 2) [10,11,12] ++
map2_List (+) [3] [10,11,12]
== map (+ 1) [10,11,12] ++
map (+ 2) [10,11,12] ++
map (+ 3) [10,11,12] ++
map2_List (+) [] [10,11,12]
== map (+ 1) [10,11,12] ++
map (+ 2) [10,11,12] ++
map (+ 3) [10,11,12] ++
[]
== [11,12,13] ++
map (+ 2) [10,11,12] ++
map (+ 3) [10,11,12] ++
[]
== [11,12,13] ++
[12,13,14] ++
map (+ 3) [10,11,12] ++
[]
== [11,12,13] ++
[12,13,14] ++
[13,14,15] ++
[]
== [11,12,13,12,13,14,13,14,15]
实例用于列表:
Applicative
您似乎正在考虑的版本将并行解构两个列表:
map2_List f as bs = f <$> as <*> bs
已定义为map2_ZipList f [] [] = []
map2_ZipList f (a:as) (b:bs) = f a b : map2_ZipList as bs
:
zipWith
答案 1 :(得分:0)
您不清楚这是如何工作的:
map2_List :: (a -> b -> c) -> [a] -> [b] -> [c]
map2_List f [] _ = []
map2_List f (a:as) bs = map (f a) bs ++ map2_List f as bs
为清楚起见,将其重新编写为列表理解:
map2_List f as bs = concat [ map (f a) bs | a <- as]
= [ r | a <- as, r <- map (f a) bs]
= [ r | a <- as, r <- [(f a) b | b <- bs]]
= [ r | a <- as, r <- [ f a b | b <- bs]]
= [ r | a <- as, b <- bs, r <- [f a b]]
= [ f a b | a <- as, b <- bs]
您会发现它等同于通常的命令式嵌套循环,
for a in as :
for b in bs :
yield (f a b)
并且确实在嵌套组合的f
中的a
和as
中的b
的每对bs
上应用了函数window.location.hash = '#openModal';
。