001 package fj.data.fingertrees; 002 003 import fj.F; 004 import fj.P2; 005 import static fj.P.p; 006 import fj.pre.Ord; 007 008 /** 009 * A tree with a single element. 010 */ 011 public final class Single<V, A> extends FingerTree<V, A> { 012 private final A a; 013 private final V v; 014 015 Single(final Measured<V, A> m, final A a) { 016 super(m); 017 this.a = a; 018 v = m.measure(a); 019 } 020 021 /** 022 * @see fj.data.fingertrees.FingerTree#foldRight(fj.F, Object) 023 */ 024 @Override public <B> B foldRight(final F<A, F<B, B>> aff, final B z) { 025 return aff.f(a).f(z); 026 } 027 028 /** 029 * @see fj.data.fingertrees.FingerTree#reduceRight(fj.F) 030 */ 031 @Override public A reduceRight(final F<A, F<A, A>> aff) { 032 return a; 033 } 034 035 @Override public <B> B foldLeft(final F<B, F<A, B>> bff, final B z) { 036 return bff.f(z).f(a); 037 } 038 039 @Override public A reduceLeft(final F<A, F<A, A>> aff) { 040 return a; 041 } 042 043 @Override public <B> FingerTree<V, B> map(final F<A, B> abf, final Measured<V, B> m) { 044 return new Single<V, B>(m, abf.f(a)); 045 } 046 047 /** 048 * Returns the annotation of this tree's single element. 049 * 050 * @return the annotation of this tree's single element. 051 */ 052 public V measure() { 053 return v; 054 } 055 056 /** 057 * Pattern matching on the structure of this tree. Matches the singleton tree. 058 */ 059 @Override public <B> B match(final F<Empty<V, A>, B> empty, final F<fj.data.fingertrees.Single<V, A>, B> single, 060 final F<Deep<V, A>, B> deep) { 061 return single.f(this); 062 } 063 064 @Override public FingerTree<V, A> cons(final A b) { 065 final MakeTree<V, A> mk = mkTree(measured()); 066 return mk.deep(mk.one(b), new Empty<V, Node<V, A>>(measured().nodeMeasured()), mk.one(a)); 067 } 068 069 @Override public FingerTree<V, A> snoc(final A b) { 070 final MakeTree<V, A> mk = mkTree(measured()); 071 return mk.deep(mk.one(a), new Empty<V, Node<V, A>>(measured().nodeMeasured()), mk.one(b)); 072 } 073 074 @Override public FingerTree<V, A> append(final FingerTree<V, A> t) { 075 return t.cons(a); 076 } 077 078 @Override public P2<Integer, A> lookup(final F<V, Integer> o, final int i) { 079 return p(i, a); 080 } 081 082 /** 083 * Returns the single element of this tree. 084 * 085 * @return the single element of this tree. 086 */ 087 public A value() { 088 return a; 089 } 090 }