【发布时间】:2020-09-19 06:41:56
【问题描述】:
我是 Clojure 和函数式编程的新手。我对 Clojure 中的数据结构(例如映射、列表和向量)有一个基本概念。
我正在尝试编写一个返回嵌套映射的函数。地图在函数内正确显示。下面的代码来自read-customer-file函数
([input-list new-map place-holder]
(if (not-empty input-list)
(do
(def string-input (str (first input-list)))
(def cust-id (get (first input-list) 0))
(def cust-name (get (first input-list) 1))
(def cust-address (get (first input-list) 2))
(def cust-phone (get (first input-list) 3))
(def temp-map (conj new-map {(keyword cust-id) {:cust-name cust-name, :cust-address cust-address, :cust-phone cust-phone}}))
(read-customer-file (rest input-list) temp-map ())
)
(do
(map str new-map)
;(print (get-in new-map [:1 :cust-name]))
(print new-map)
)
)
)
这需要一个向量列表的输入,如下所示:
([3 Fan Yuhong 165 Happy Lane 345-4533] [2 Sue Jones 43 Rose Court Street 345-7867] [1 John Smith 123 Here Street 456-4567])
并返回一个嵌套映射如下:
{:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}}
这是我正在努力实现的目标,并且在该功能中运行良好。但是,如果我尝试使用返回类型的值在函数外部定义一个变量,我不会得到一个嵌套映射,而是一个字符串列表。为此,我只删除了(print new-map) 部分。
(do
(map str new-map)
)
并从函数定义之外调用它,如下所示:
(def customer-info-list read-customer-file)
(println (customer-info-list))
得到的结果与我的预期不同,无法执行get和get-in等地图相关功能。
([:3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}] [:2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}] [:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}])
我非常感谢任何形式的帮助。我知道我的代码有点乱,我应该使用let 而不是def 作为变量名。但我刚刚开始使用 Clojure,这是我的第一个程序。
更新
我解决了这个问题。我所做的是将地图更改为函数内的排序地图。所以函数的最后一个返回将是一个排序的映射。
(do
(into (sorted-map) new-map)
)
但是,如果分配给变量,返回的值仍然是一个字符串。所以我再次将其转换为排序映射。然后它最终被转换为嵌套地图。
(def customer-info-list read-customer-file)
(def cust-map (into (sorted-map) (customer-info-list)))
(println cust-map)
(println (get-in cust-map [:1 :cust-name]))
(println (get cust-map :2))
以上三个打印语句的输出与预期一致。
{:1 {:cust-name John Smith, :cust-address 123 Here Street, :cust-phone 456-4567}, :2 {:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}, :3 {:cust-name Fan Yuhong, :cust-address 165 Happy Lane, :cust-phone 345-4533}}
John Smith
{:cust-name Sue Jones, :cust-address 43 Rose Court Street, :cust-phone 345-7867}
【问题讨论】:
-
def-ing 在你的函数中通常是你不想做的事情。请改用let。
标签: clojure functional-programming