使用 toList 不好吗?

发布于 2024-09-26 06:12:28 字数 854 浏览 0 评论 0原文

假设有 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

习ぎ惯性依靠 2024-10-03 06:12:28

在地图上使用 foldintersectWith 更优雅(而且可能更快):

combi :: M.Map Int Float -> M.Map Int Float -> Float
combi x y = M.fold (+) 0 $ M.intersectionWith (*) x y

combi稀疏1稀疏2返回414.0 根据需要。

如果您关心性能,请尝试使用 Data.IntMap:它应该比这里的 Data.Map 快几倍。

Using fold and intersectWith on the maps is a bit more elegant (and probably faster):

combi :: M.Map Int Float -> M.Map Int Float -> Float
combi x y = M.fold (+) 0 $ M.intersectionWith (*) x y

combi sparse1 sparse2 returns 414.0 as desired.

And if you care about performance, try using Data.IntMap: it should be several times faster than Data.Map here.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文