Clojure 中的自定义相等不同 [英] Custom equality in Clojure distinct

查看:22
本文介绍了Clojure 中的自定义相等不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 Clojure 程序中,我有一个由包含人们姓名和电子邮件的映射组成的数组.

例如

<预><代码>[{ :name "John" :email "john@gmail.com" }{ :name "蝙蝠侠" :email "batman@gmail.com" }{ :name "John Doe" :email "john@gmail.com" }]

我想删除重复的条目,为了比较目的,具有相同电子邮件的对是相等的.在上面的示例中,输出将是:

<预><代码>[{ :name "John" :email "john@gmail.com" }{ :name "蝙蝠侠" :email "batman@gmail.com" }]

在 Clojure 中实现这一目标的最佳方法是什么?有没有办法让 distinct 知道要使用什么等于函数?

谢谢.

解决方案

这样做:https://crossclj.info/fun/medley.core/distinct-by.html.

链接中的函数懒惰地遍历每个值并存储它看到的所有内容.如果已经看到 coll 中的值,则不添加它.

然后您可以将其称为:(distinct-by #(% :email) maps),其中 maps 是您的人物地图向量.

In a Clojure program I've an array composed by maps containing peoples' names and emails.

e.g.

[
    { :name "John" :email "john@gmail.com" }  
    { :name "Batman" :email "batman@gmail.com" }  
    { :name "John Doe" :email "john@gmail.com" }  
 ] 

I'd like to remove the duplicate entries considering, for comparison purposes, pairs having the same e-mail to be equals. In the example above the output would be:

[
    { :name "John" :email "john@gmail.com" }  
    { :name "Batman" :email "batman@gmail.com" }  
 ] 

What's the best way to achieve this in Clojure? Is there a way to let distinct knows what equals function to use?

Thanks.

解决方案

This would do it: https://crossclj.info/fun/medley.core/distinct-by.html.

The function in the link goes through every value lazily and stores everything it's seen. If the value in the coll is already seen, it does not add it.

You could then call this as: (distinct-by #(% :email) maps), where maps is your vector of people-maps.

这篇关于Clojure 中的自定义相等不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆