All Downloads are FREE. Search and download functionalities are using the official Maven repository.

fj.data.Writer Maven / Gradle / Ivy

Go to download

Functional Java is an open source library that supports closures for the Java programming language

There is a newer version: 5.0
Show newest version
package fj.data;

import fj.*;

/**
 * Created by MarkPerry on 7/07/2014.
 */
public final class Writer {

	private final A val;
	private final W logValue;
	private final Monoid monoid;

	private Writer(A a, W w, Monoid m) {
		val = a;
		logValue = w;
        monoid = m;
	}

	public P2 run() {
		return P.p(logValue, val);
	}

	public A value() {
		return val;
	}

	public W log() {
		return logValue;
	}

	public Monoid monoid() {
		return monoid;
	}

	public static  Writer unit(A a, W w, Monoid m) {
		return new Writer<>(a, w, m);
	}

    public static  Writer unit(A a, Monoid m) {
        return new Writer<>(a, m.zero(), m);
    }

    public Writer tell(W w) {
		return unit(val, monoid.sum(logValue, w), monoid);
	}

	public  Writer map(F f) {
		return unit(f.f(val), logValue, monoid);
	}

	public  Writer flatMap(F> f) {
		Writer writer = f.f(val);
		return unit(writer.val, writer.monoid.sum(logValue, writer.logValue), writer.monoid);
	}

	public static  Writer unit(B b) {
		return unit(b, Monoid.stringMonoid);
	}

	public static  F> stringLogger() {
		return a -> unit(a, Monoid.stringMonoid);
	}

}