Move map list

I am new to Clojure and I have a simple question

Suppose I have a List of Maps. Each Card has: name and age:

My code is:

(def Person {:nom rob :age 31 } )
(def Persontwo {:nom sam :age 80 } )
(def Persontthree {:nom jim :age 21 } )
(def mylist (list Person Persontwo Personthree))

Now how do I go through the list. Say, for example, that I have a given name. How to iterate over a list to see if any of the Maps name matches: my: name. And then, if there is a card that matches, how do I get the index position of this card?

-Thanks

+3
source share
6 answers
(defn find-person-by-name [name people] 
   (let
      [person (first (filter (fn [person] (= (get person :nom) name)) people))]
      (print (get person :nom))
      (print (get person :age))))

EDIT : The above was the answer to the question, as it was before the question was edited; updated here - filterand mapstarted to get confused, so I rewrote it from scratch with loop:

; returns 0-based index of item with matching name, or nil if no such item found
(defn person-index-by-name [name people] 
    (loop [i 0 [p & rest] people]
        (cond
            (nil? p)
                nil
            (= (get p :nom) name) 
                i
            :else
                (recur (inc i) rest))))
+2

doseq:

(defn print-person [name people]
  (doseq [person people]
    (when (= (:nom person) name)
      (println name (:age person)))))
+2

. , . ( , , ), .

+2

, . ( , ).

...

(defn first-index-of [key val xs]
  (loop [index 0
         xs xs]
    (when (seq xs)
      (if (= (key (first xs)) val)
        index
        (recur (+ index 1)
               (next xs))))))

:

> (first-index-of :nom 'sam mylist)
1
> (first-index-of :age 12 mylist)
nil
> (first-index-of :age 21 mylist)
2
+1

positions clojure.contrib.seq (Clojure 1.2)?

(use '[clojure.contrib.seq :only (positions)])
(positions #(= 'jim (:nom %)) mylist)

( first take, ).

0
(defn index-of-name [name people]
  (first (keep-indexed (fn [i p]
                         (when (= (:name p) name)
                           i))
                       people)))

(index-of-name "mark" [{:name "rob"} {:name "mark"} {:name "ted"}])
1
0
source

Source: https://habr.com/ru/post/1712531/


All Articles