Free Clojure course. Sign Up for tracking progress →

Clojure: Еще немного о хешах

В Clojure с помощью хеш-мап очень легко задать полиморфное поведение (есть еще специальный механизм defmulti о нем чуть позже). К тому же, имеется богатая библиотека по обработке коллекций. Рассмотрим еще несколько примеров:

; Создадим простой калькулятор с помощью хеш-мапы
(defn calc [first-num second-num operation]
  (let [operations-map {"+" +
                        "-" -
                        "*" *
                        "^" (fn [a b] (int (Math/pow a b)))}]
  ((operations-map operation) first-num second-num)))

(calc 2 3 "+") ; => 5
(calc 2 3 "-") ; => -1
(calc 2 3 "*") ; => 6
(calc 2 3 "^") ; => 8

; еще немного функций для работы с хешами
(def company
  {:name "WidgetCo"
   :address {:street "123 Main St"
             :city "Springfield"
             :state "IL"}})

; обратимся к вложенному хешу
(get-in company [:address :state])

; теперь обновим вложенный хеш
(assoc-in company [:address :street] "303 Broadway")

; => {:name "WidgetCo",
; => :address {:state "IL",
; =>           :city "Springfield",
; =>           :street "303 Broadway"}}

(def scores {"Andrew" 100 "Angela" 200})
(merge scores {"Kim" 150 "Ivan" 200})
; => {"Andrew" 100, "Angela" 200, "Kim" 150, "Ivan" 200}


Создайте функцию freq, которая принимает коллекцию элементов и создает хеш-мапу с частотой появления элементов в коллекции. Больше подробностей в примерах.

(freq ["a" "b" "c" "a" "a" "c" "a" "d" "b"])
; => {"a" 4, "b" 2, "c" 2, "d" 1}

(freq [])
; => {}

(freq ["Clojure" "Ruby" "Clojure" "Elixir" "Ruby" "HTML" "JS"])
; => {"Clojure" 2, "Ruby" 2, "Elixir" 1, "HTML" 1, "JS" 1}

(freq [10 10 10 20 300 41 53])
; => {10 3, 20 1, 300 1, 41 1, 53 1}

(freq [:a :b :c :d :a :a])
; => {:a 3, :b 1, :c 1, :d 1}
The exercise doesn't pass checking. What to do? 😶

If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:

  • Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
In my environment the code works, but not here 🤨

Tests are designed so that they test the solution in different ways and against different data. Often the solution works with one kind of input data but doesn't work with others. Check the «Tests» tab to figure this out, you can find hints at the error output.

My code is different from the teacher's one 🤔

It's fine. 🙆 One task in programming can be solved in many different ways. If your code passed all tests, it complies with the task conditions.

In some rare cases, the solution may be adjusted to the tests, but this can be seen immediately.

I've read the lessons but nothing is clear 🙄

It's hard to make educational materials that will suit everyone. We do our best but there is always something to improve. If you see a material that is not clear to you, describe the problem in “Discussions”. It will be great if you'll write unclear points in the question form. Usually, we need a few days for corrections.

By the way, you can participate in courses improvement. There is a link below to the lessons course code which you can edit right in your browser.

If you got stuck and don't know what to do, you can ask a question in our huge and friendly community