Branches by Matching

Machine Learning Artificial Intelligence Digital Transformation Programming Technology ICT Technology Clojure Javascript CSS Web Technologies Navigation of this blog
Branches by Matching

The basis of algorithms is branching and iteration. In any programming language, if you learn branching, iteration, input/output, data structures (and how to introduce libraries), you will be able to do the basic operations.

In Clojure, branching can be done almost completely with if or condition.

(defn is-small? [number]
  (if (< number 100) "yes" "no"))

user=> (is-small? 50)
"yes"

user=> (is-small? 500)
"no"

In this way, the multi-branch, COND, looks like the following.

(defn pos-neg-or-zero
  "Determines whether or not n is positive, negative, or zero"
  [n]
  (cond
    (< n 0) "negative"
    (> n 0) "positive"
    :else "zero"))

user=> (pos-neg-or-zero 5)
"positive"
user=> (pos-neg-or-zero -1)
"negative"
user=> (pos-neg-or-zero 0)
"zero"

A derivative of cond is condp. This is a simple way to write responses to multiple input matches. For example

(defn condp-test1
  [coll]
  (condp some coll
    #{1 2 3} "coll contains 1 or 2 or 3"
    #{4 5 6} "coll contains 4 or 5 or 6"
    "coll is other"))

(println (condp-test-2 [1 2 3 4]))  ;; coll contains 1 or 2 or 3
(println (condp-test-2 [4]))  ;; coll contains 4 or 5 or 6
(println (condp-test-2 [7 8 9]))  ;; coll is other

or

(defn condp-test2
   [coll]
   (condp some coll
      #{"aaa" "bbb" "ccc" "ddd"}  "マッチしました"
      "マッチしませんでした"))
(condp-test2 ["bbb" "ddd"])
-> "マッチしました"

In addition, there are branches that do not use if and condition, such as defun and match. In addition, there are branches that do not use if and condition, such as defun and match. defun can be used to write a branch when a specific string is entered, as shown below.

(use '[defun :only [defun]])
(defun greet
  (["JoJo"] "誇りの道を往く者に太陽の輝きを")
  (["Dio"] "野望の果てを目指すものに生贄を")
  ([x]  (format "こんにちは,%sさん" x)))

(greet "JoJo")
;; => "誇りの道を往く者に太陽の輝きを"
(greet "Dio")
;; => "野望の果てを目指すものに生贄を"
(greet "Tom")
;; => "こんにちは,Tomさん"

The match will be when it is more than one.

(require '[clojure.core.match :refer [match]])
(doseq [n (range 1 101)]
  (println
    (match [(mod n 3) (mod n 5)]
      [0 0] "FizzBuzz"
      [0 _] "Fizz"
      [_ 0] "Buzz"
      :else n)))

 

コメント

タイトルとURLをコピーしました