Find prime numbers using Scala. Help me to improve

Here’s a functional implementation of the Sieve of Eratosthenes, as presented in Odersky’s “Functional Programming Principles in Scala” Coursera course : // Sieving integral numbers def sieve(s: Stream[Int]): Stream[Int] = { s.head #:: sieve(s.tail.filter(_ % s.head != 0)) } // All primes as a lazy sequence val primes = sieve(Stream.from(2)) // Dumping the first five … Read more

Abusing the algebra of algebraic data types – why does this work?

Disclaimer: A lot of this doesn’t really work quite right when you account for ⊥, so I’m going to blatantly disregard that for the sake of simplicity. A few initial points: Note that “union” is probably not the best term for A+B here–that’s specifically a disjoint union of the two types, because the two sides … Read more

How to compose functions in Rust?

As @ljedrz points out, to make it work you only need to reference the composed functions again: let finally = compose(&*multiply_and_add, &*divide_and_subtract); (Note that in Rust, convention dictates that variable names should be in snake_case) However, we can make this better! Since Rust 1.26, we can use abstract return types (previously featured gated as #![feature(conservative_impl_trait)]). … Read more

Finding enum value with Java 8 Stream API

I would use findFirst instead: return Arrays.stream(Type.values()) .filter(e -> e.s.equals(val)) .findFirst() .orElseThrow(() -> new IllegalStateException(String.format(“Unsupported type %s.”, val))); Though a Map could be better in this case: enum Type{ X(“S1”), Y(“S2”); private static class Holder { static Map<String, Type> MAP = new HashMap<>(); } private Type(String s) { Holder.MAP.put(s, this); } public static Type find(String … Read more