Back
monoid (clj)
(source)function
(monoid op ctor)
Builds a combining fn out of the supplied operator and identity
constructor. op must be associative and ctor called with no args
must return an identity value for it.
Examples
aphyr/tesser
(ns tesser.simple-test
(:require [clojure.test :refer :all]
[clojure.test.check :as tc]
[clojure.test.check [clojure-test :refer :all]
[generators :as gen]
[properties :as prop]]
[multiset.core :refer [multiset]]
[tesser.simple :as s]
[clojure.core.reducers :as r]
[clojure.set :as set]))
(defspec fold-spec
test-opts
(let [reducer (r/monoid conj hash-set)]
(prop/for-all [xs flat-ints]
(and (is (= (r/fold + xs)
(s/fold + xs)))
(is (= (r/fold set/union reducer xs)
(s/fold set/union reducer xs)))))))
uncomplicate/fluokitten
(ns uncomplicate.fluokitten.core-test
(:use [uncomplicate.fluokitten algo jvm core test utils])
(:use [midje.sweet :exclude [just]])
(:require [clojure.string :as s]
[clojure.core.reducers :as r]))
(monoid-identity-law [1 2])
(monoid-identity-law (long-array [1 2]))
(monoid-identity-law (list 1 2))
(monoid-identity-law (lazy-seq (list 1 2)))
(monoid-identity-law (eduction (list 1 2)))
(monoid-identity-law (seq (list 1 2)))
(monoid-identity-law #{1 2})
(monoid-identity-law {:a 1 :b 2})
(monoid-identity-law (first {:a 1}))
(monoid-identity-law "something")
(monoid-identity-law 4)
(monoid-identity-law :something)
(monoid-identity-law (atom 4))
(monoid-identity-law (volatile! 4))
(dosync (monoid-identity-law (ref 5)))
(monoid-identity-law +)
(monoid-identity-law c+))
(monoid-identity-law (just :something))
damballa/parkour
(ns parkour.reducers-test
(:require [clojure.core.reducers :as r]
[parkour (reducers :as pr)]
[clojure.test :refer :all]))
(deftest test-reduce-by
(testing "Explicit init value"
(is (= [[1 1 1] [2 2 2] [3 3 3]]
(->> [1 1 1 2 2 2 3 3 3]
(pr/reduce-by identity conj [])
(into []))))
(is (= [[1 1 1]]
(->> [1 1 1 2 2 2 3 3 3 4 4 4]
(pr/reduce-by identity conj [])
(r/take 1)
(into []))))
(is (= [[1 1 1] [2 2 2]]
(->> [1 1 1 2 2 2 3 3 3 4 4 4]
(r/take 6)
(pr/reduce-by identity conj [])
(into []))))
(is (= [[1 1 1] [2 2 2]]
(->> [1 1 1 2 2 2 3 3 3 4 4 4]
(pr/reduce-by identity conj [])
(r/take 2)
(into []))))
(is (= []
(->> [1 1 1 3 3 3 5 5 5 7 7 7]
(r/filter even?)
(pr/reduce-by identity conj [])
(into [])))))
(testing "Init value from monoid"
(is (= [3 4]
(->> [1 1 1 2 2 2 3 3 3 4 4 4]
(r/take 5)
(pr/reduce-by identity +)
(into []))))))
reborg/clojure-essential-reference
(require '[clojure.core.reducers :as r]) ; <1>
(r/fold
(r/monoid str (constantly "Concatenate ")) ; <2>
["th" "is " "str" "ing"])
;; "Concatenate this string"