Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how can the clojure.algo.generic library be used?

Tags:

clojure

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

say if I wanted to implement vector addition, etc:

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

how would I go about:

  • defining the + operator with algo.generic
  • using the + operator previously defined within another project?
like image 757
zcaudate Avatar asked Sep 26 '12 01:09

zcaudate


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))
like image 124
kotarak Avatar answered Oct 02 '22 01:10

kotarak


edit 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])

-- Edit --

You should use (require [lib :as namespacehere]) and call (namespacehere/+ ...). Below is the code for the problem presented.

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

Also, check out (in-ns).

like image 26
runexec Avatar answered Oct 02 '22 03:10

runexec