簡體   English   中英

Clojure:如何從元組中獲取特定值

[英]Clojure: How to obtain a specific value from a tuple

我一直在Clojure中構建自己的項目,我希望通過搜索前兩個值並獲得第三個值來獲取此元組的值。

我一直在搜索,我找不到問題的解決方案,我想構建一個函數,在每個特定的向量中要求兩個前兩個值,這樣它就會得到第三個。

這是迄今為止的元組。

(def cars
'#{[has car wheels]
   [has car radio]
   [has vauxhall suspension]
   [colour vauxhall red]
   [colour ford blue]
   [is vauxhall car]
   [is ford car]})

因此,例如,如果我構建了一個名為“search”的函數並放入向量的前兩個值,那就像這樣

user   => (search 'has 'vauxhall)
answer => suspension

因為元組中的那個向量是[有vauxhall懸掛]

我只是好奇有沒有辦法做到這一點? 因為我在網上找不到任何進程,但是我想構建一個能夠執行它的函數(比如我提出的搜索函數),而不是任何能讓我得到答案的REPL快捷方式。

我將不勝感激任何幫助或輸入:)

這是一種方法。

(def cars
  #{[:has :car :wheels]
    [:has :car :radio]
    [:has :vauxhall :suspension]
    [:colour :vauxhall :red]
    [:colour :ford :blue]
    [:is :vauxhall :car]
    [:is :ford :car]})

(defn search [word1 word2]
  (some (fn [[w1 w2 w3]]
          (and (= word1 w1) (= word2 w2) w3)
        cars))

(search :has :vauxhall)
;; =>:suspension

注意我將元素編碼為關鍵字而不是符號 - 關鍵字評估為自己。

搜索功能使用了some

返回coll中任何x的第一個邏輯真值(pred x),否則為nil。

如果所有參數都為true and返回最后一個參數。 在這種情況下,這是所請求的元素。

這只返回第一個匹配,如果你想要它們,你可以使用reduce

(defn search [word1 word2]
  (reduce
   (fn [acc [w1 w2 w3]]
     (if (and (= word1 w1) (= word2 w2))
       (conj acc w3)
       acc))
   #{}
   cars))

(search :has :car)
;; => #{:radio :wheels}

不確定你的用例是什么,但如果你把它建模為嵌套地圖那么問題將是很簡單的

(def cars
  {:has {:car [:wheel :radio]
         :vauxhall :suspension}
   :color {:vauxhall :red
           :ford :blue}
   :is {:vauxhall :car
        :ford :car}})

(get-in cars [:has :vauxhall]) ; => :suspension
(get-in cars [:has :car])      ; =>[:wheel :radio]

get-in允許您輕松查詢嵌套映射,大大簡化了代碼。

再次不確定您的用例是什么,但將列表查詢轉換為此嵌套地圖結構將非常容易。

我會使它更通用,提供一個通過前綴獲取數據的功能

user> (defn with-prefix [prefix data]
        (filter #(= prefix (take (count prefix) %)) data))
#'user/with-prefix


user> (->> cars
           (with-prefix '[has vauxhall])
           first
           last)

;;=> suspension

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM