【问题标题】:How to return a map in clojure如何在clojure中返回地图
【发布时间】:2016-02-17 04:20:54
【问题描述】:

我想知道如何定义一个函数,它将返回一个地图。现在我有两个辅助功能。 一个是:

(string->ascii str) 

可以将字符串转换成ascii码,比如:

user=> (string->ascii "ouch")
(79 85 67 72)
user=> (string->ascii "gulp")
(71 85 76 80)

另一个函数是:

(ascii->num96 seq)

可以将列表转换成小数,比如:

user=> (ascii-num96 '(79 85 67 72))
70684008
user=> (ascii-num96 '(71 85 76 80))
63606992

现在,我需要定义一个函数“make-dict”,同时调用这两个函数并返回一个地图。结果应该是:

user=> (make-dict ["ouch" "gulp"])
{"ouch" 70684008, "gulp" 63606992}

我写了一些代码,但它不起作用,比如:

(defn make-dict [vector]
(map (ascii-num96 #(string-ascii %)) vector))

有没有人可以教如何获得这样的结果?非常感谢!

【问题讨论】:

    标签: clojure


    【解决方案1】:

    这个怎么样?

    (defn make-dict [words]
      (zipmap words (map (comp ascii-num96 string->ascii) words)))
    

    你基本上需要 2 个序列——words(map (comp ascii-num96 string->ascii) words)——然后将它们压缩成一张地图。

    【讨论】:

    • 知道了!非常感谢!我还有一个问题,如果 words 中的元素数量与 (map (comp ascii-num96 string->ascii) words) 中的元素数量不匹配,它会成功 zipmap 吗?谢谢!
    • 你能想到xs 的长度与(map f xs) 不同的场景吗?
    • 同上@amalloy 所说的。但是让我们假设一个不相关的场景——如果你有 2 个输入 seq,xsys,那么就像 mapzipmap 函数在最短的 seq 完全消耗后停止消耗输入 seq(之后(min (count xs) (count ys)) 元素)。
    【解决方案2】:

    或者没有zipmap:

    (into {} (map vector names (map (comp ascii-num96 string->ascii) names)))
    

    发生的两件事可能很有趣,有点像“技巧”。一种是您可以将map 与许多输入序列一起使用,您的“映射函数”只需要能够处理相同数量的参数。这里的映射函数是vector,它把一个单词和一个数字放在一起,像这样:["gulp" 34234]。

    另一件事是函数into 将向量解释为键/值对。

    【讨论】:

      猜你喜欢
      • 2020-09-19
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 2015-04-18
      • 1970-01-01
      • 2014-10-07
      • 1970-01-01
      相关资源
      最近更新 更多