使用 toList 不好吗?
假设有 2 个映射,
import qualified Data.Map as M
sparse1, sparse2 :: M.Map Int Float
sparse1 = M.fromList [(1,2.0),(10,3),(12,5),(100,7),(102,11)]
sparse2 = M.fromList [(2,13.0),(11,17),(12,19),(101,23),(102,29)]
您如何定义一个优雅的函数
combi :: M.Map Int Float -> M.Map Int Float -> Float
,使 Combi稀疏1稀疏2返回414.0(= 5 * 19 + 11 * 29),因为12和102是两个映射的唯一公共键?有一个带有列表的优雅(简单且高效)的函数,因为这些列表是严格排序的:
combiList xs ys = cL xs ys 0
cL [] _ acc = acc
cL _ [] acc = acc
cL (x@(k,r):xs) (y@(k',r'):ys) acc
| k < k' = cL xs (y:ys) acc
| k == k' = cL xs ys (acc+r*r')
| k > k' = cL (x:xs) ys acc
但是
combi m1 m2 = combiList (M.toList m1) (M.toList m2)
知道列表不再在代码的其余部分中使用是一个好主意吗?如果没有,你如何在没有 toList 的情况下有效地编写组合?
Suppose 2 Maps
import qualified Data.Map as M
sparse1, sparse2 :: M.Map Int Float
sparse1 = M.fromList [(1,2.0),(10,3),(12,5),(100,7),(102,11)]
sparse2 = M.fromList [(2,13.0),(11,17),(12,19),(101,23),(102,29)]
How do you define an elegant function
combi :: M.Map Int Float -> M.Map Int Float -> Float
such that combi sparse1 sparse2 returns 414.0 (= 5 * 19 + 11 * 29) because 12 and 102 are the only common keys of the two maps ? There is an elegant (simple and efficient) function with lists since those would be strictly ordered:
combiList xs ys = cL xs ys 0
cL [] _ acc = acc
cL _ [] acc = acc
cL (x@(k,r):xs) (y@(k',r'):ys) acc
| k < k' = cL xs (y:ys) acc
| k == k' = cL xs ys (acc+r*r')
| k > k' = cL (x:xs) ys acc
But is
combi m1 m2 = combiList (M.toList m1) (M.toList m2)
a good idea knowing the lists are no more used in the rest of the code ? And if not, how would you efficiently write combi without toList ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在地图上使用
fold
和intersectWith
更优雅(而且可能更快):combi稀疏1稀疏2
返回414.0
根据需要。如果您关心性能,请尝试使用
Data.IntMap
:它应该比这里的Data.Map
快几倍。Using
fold
andintersectWith
on the maps is a bit more elegant (and probably faster):combi sparse1 sparse2
returns414.0
as desired.And if you care about performance, try using
Data.IntMap
: it should be several times faster thanData.Map
here.