Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
//License from project: Open Source License 

import java.util.ArrayList;

import java.util.Collections;
import java.util.List;

import java.util.function.Function;

public class Main {
    public static <X, Y> List<Y> mapWithFoldr(List<X> xs, Function<X, Y> mapper) {
        return foldr(xs, Collections.emptyList(), x -> res -> cons(mapper.apply(x), res));
    }

    public static <V, X> V foldr(List<X> xs, V v, Function<X, Function<V, V>> f) {
        if (xs.size() == 0) {
            return v;
        }
        return f.apply(head(xs)).apply(foldr(tail(xs), v, f));
    }

    public static <A> List<A> cons(A a, List<A> as) {
        List result = new ArrayList<>(as);
        result.add(0, a);
        return Collections.unmodifiableList(result);
    }

    public static <A> A head(List<A> list) {
        return list.get(0);
    }

    public static <A> List<A> tail(List list) {
        List result = new ArrayList<>(list);
        result.remove(0);
        return Collections.unmodifiableList(result);
    }
}