How can I use the clojure.algo.generic library?

I know that the https://github.com/clojure/algo.generic library provides ways to implement common arithmetic operators + * / -, but there I could not find a simple example of how to create them, and then how to use it as a library.

let's say if I wanted to implement adding vectors, etc .:

> (+ [1 2 3 4 5] 5) 
;; => [6 7 8 9 10]

How can I:

  • operator definition +using algo.generic
  • using an operator +previously defined in another project?
+5
source share
2 answers
(ns your.custom.operators
  (:import
    clojure.lang.IPersistentVector)
  (:require
    [clojure.algo.generic.arithmetic :as generic]))

(defmethod generic/+
  [IPersistentVector Long]
  [v x]
  (mapv + v (repeat x)))

(ns your.consumer.project
  (:refer-clojure :exclude (+))
  (:use
    [clojure.algo.generic.arithmetic :only (+)])
  (:require
    your.custom.operators))

(defn add-five
  [v]
  (+ v 5))
+4
source

change 2,

user=> (defn + [coll i] (map #(clojure.core/+ % i) coll))
#'user/+
user=> (+ [1 2 3 4 5] 5)
(6 7 8 9 10)

edit, you can also do

(in-ns 'algo.generic)
(defn + [& args])

- Change -

(require [lib: as namespacehere]) (namespacehere/+...). .

user=> (map #(+ % 5) [1 2 3 4 5])
(6 7 8 9 10)

, (in-ns).

+1

All Articles