Scala equivalent to Haskell's sequence - scala

Is there a Scala Library method that performs the conversion Seq[Option[T]] -> Option[Seq[T]]?
The Haskell equivalent would be sequence :: Monad m => [m a] -> m [a].

This is unfortunately not available in the standard library (although there is a Future.sequence, as pedrofurla points out above). Part of the reason for this is probably just that the Scala standard library doesn't have any idea about applicative functors (or even monads, really).
As pedrofurla also mentions above, Scalaz does provide sequence, and it's actually a lot more appropriately typed than Haskell's—instead of requiring something monadic inside a list as input, it accepts anything with an applicative functor instance inside something with a traversable instance (i.e., it's equivalent to Data.Traversable's sequenceA in Haskell, not the sequence in the Prelude).

Related

A type constructor IS a monad or HAS a monad?

People usually say a type IS a monad.
In some functional languages and libraries (like Scala/Scalaz), you have a type constructor like List or Option, and you can define a Monad implementation that is separated from the original type. So basically there's nothing that forbids you in the type system from creating distinct instances of Monad for the same type constructor.
is it possible for a type constructor to have multiple monads?
if yes, can you provide any meaningful example of that? any "artificial" one?
what about monoids, applicatives... ?
You can commonly find this all around in mathematics.
A monad is a triple (T, return, bind) such that (...). When bind and return can be inferred from the context, we just refer to the monad as T.
A monoid is a triple (M, e, •) such that (...). (...) we just refer to the monoid as M.
A topological space is a pair (S, T) such that (...). We just refer to the topological space as S.
A ring is a tuple (V, 0, +, 1, ×)...
So indeed, for a given type constructor T there may be multiple different definitions of return and bind that make a monad. To avoid having to refer to the triple every time, we can give T different names to disambiguate, in a way which corresponds to the newtype construct in Haskell. For example: [] vs ZipList, State s vs ReaderT s (Writer s).
P.S. There is something artificial in saying that a monad or a monoid is a triple, especially given that there are different presentations: we could also say that a monad is a triple (T, fmap, join), or that a monoid is a pair (M, •), with the identity element hidden in the extra condition (because it is uniquely determined by • anyway). The ontology of mathematical structures is a more philosophical question that is outside the scope of SO (as well as outside my expertise). But a more prudent way to reformulate such definitions may be to say that "a monad is (defined|characterized) by a triple (T, return, bind)".
Insofar as you're asking about language usage, Google says that the phrase “has a monad” doesn't seem to be commonly used in the way you're asking about. Most real occurrences are in sentences such as, “The Haskell community has a monad problem.” However, a few cases of vaguely similar usage do exist in the wild, such as, “the only thing which makes it ‘monadic‘ is that it has a Monad instance.” That is, monad is often used as a synonym for monadic, modifying some other noun to produce a phrase (a monad problem, a Monad instance) that is sometimes used as the object of the verb have.
As for coding: in Haskell, a type can declare one instance of Monad, one of Monoid and so on. When a given type could have many such instances defined, such as how numbers are monoids under addition, multiplication, maximum, minimum and many other operations, Haskell defines separate types, such as Sum Int, a Monoid instance over Int where the operation is +, and Product Int, a Monoid instance where the operation is *.
I haven't comprehensively checked the tens of thousands of hits, though, so it's very possible there are better examples in there of what you're asking about.
The phrasing I've commonly seen for that is the one I just used: a type is a category under an operation.

When to use monads from scalaz?

I'd like to create a simple wrapper for computations. The built-in scala monads (TraversableLike) seems sufficient for me. And they have already syntax sugar. From some point of view scala collection traits are accidental monads. And there intended monads provided by the scalaz library.
What uses cases benefit from complex type classed monads of scalaz? What functionality is unfeasible for built-in monads and indicate need for scalaz?
Some clarification.
This question is not a holy war inheritance vs type classes. My question is about infrastructure that provides scalaz. Not any library with type classes approach, but this mentioned library. It slightly complicates things. But also it have bunch of utility classes that have no matches in scala collection library. Because it is a collection library, not a monadic. So the question is about the additional functionality provided by scalaz. In which cases does it matter?
First for a point about terminology: it's sometimes useful shorthand to say things like "Option is a monad", but "Option has a monad instance" or "Option is monadic" is clearer. It's potentially a little confusing to say that Scalaz provides a bunch of monads—what it provides is a Monad type class and instances of that type class for a number of types, including some of its own (e.g. \/, Task, etc.) and some from the standard library (List, Option, etc.).
So I'm going to answer a question which is similar to your question: what's the value of an explicit Monad type class over the monadic syntactic sugar provided by the standard library?
One place where having an explicit Monad representation is useful is when you want to define your own generic combinators or operations. Suppose I want to write a method addM that takes two monadic M[Int] values and adds them in the monad. It's easy to write for Option:
def addM(oa: Option[Int], ob: Option[Int]): Option[Int] = for {
a <- oa
b <- ob
} yield a + b
Or for lists:
def addM(oa: List[Int], ob: List[Int]): List[Int] = for {
a <- oa
b <- ob
} yield a + b
These two implementations obviously have a lot in common, and it'd be nice to be able to write a single generic implementation that would work in both cases—and for any other monadic type as well. This is really hard if we only have the standard library's hand-wavy monadic syntax, and really easy if we have a Monad type class.

What exactly makes Option a monad in Scala?

I know what the monads are and how to use them. What I don't understand is what makes, let's say, Option a monad?
In Haskell a monad Maybe is a monad because it's instantiated from Monad class (which has at least 2 necessary functions return and bind that makes class Monad, indeed, a monad).
But in Scala we've got this:
sealed abstract class Option[+A] extends Product with Serializable { ... }
trait Product extends Any with Equals { ... }
Nothing related to a monad.
If I create my own class in Scala, will it be a monad by default? Why not?
Monad is a concept, an abstract interface if you will, that simply defines a way of composing data.
Option supports composition via flatMap, and that's pretty much everything that is needed to wear the "monad badge".
From a theoretical point of view, it should also:
support a unit operation (return, in Haskell terms) to create a monad out of a bare value, which in case of Option is the Some constructor
respect the monadic laws
but this is not strictly enforced by Scala.
Monads in scala are a much looser concept that in Haskell, and the approach is more practical.
The only thing monads are relevant for, from a language perspective, is the ability of being used in a for-comprehension.
flatMap is a basic requirement, and you can optionally provide map, withFilter and foreach.
However, there's no such thing as strict conformance to a Monad typeclass, like in Haskell.
Here's an example: let's define our own monad.
class MyMonad[A](value: A) {
def map[B](f: A => B) = new MyMonad(f(value))
def flatMap[B](f: A => MyMonad[B]) = f(value)
override def toString = value.toString
}
As you see, we're only implementing map and flatMap (well, and toString as a commodity).
Congratulations, we have a monad! Let's try it out:
scala> for {
a <- new MyMonad(2)
b <- new MyMonad(3)
} yield a + b
// res1: MyMonad[Int] = 5
Nice! We are not doing any filtering, so we don't need to implement withFilter. Also since we're yielding a value, we don't need foreach either. Basically you implement whatever you wish to support, without strict requirements. If you try to filter in a for-comprehension and you haven't implemented withFilter, you'll simply get a compile-time error.
Anything that (partially) implements, through duck-typing, the FilterMonadic trait is considered to be a monad in Scala. This is different than how monads are represented in Haskell, or the Monad typeclass in scalaz. However, in order to benefit of the for comprehension syntactic sugar in Scala, an object has to expose some of the methods defined in the FilterMonadic trait.
Also, in Scala, the equivalent of the Haskell return function is the yield keyword used for producing values out of a for comprehension. The desugaring of yield is a call to the map method of the "monad".
The way I'd put it is that there's an emerging distinction between monads as a design pattern vs. a first-class abstraction. Haskell has the latter, in the form of the Monad type class. But if you have a type that has (or can implement) the monadic operations and obeys the laws, that's a monad as well.
These days you can see monads as a design pattern in Java 8's libraries. The Optional and Stream types in Java 8 come with a static of method that corresponds to Haskell return, and a flatMap method. There is however no Monad type.
Somewhere in between you also have the "duck-typed" approach, as Ionuț G. Stan's answer calls out. C# has this as well—LINQ syntax isn't tied to a specific type, but rather it can be used with any class that implements certain methods.
Scala, per se, does not provide the notion of a monad. You can express a monad as a typeclass but Scala also doesn't provide the notion of a typeclass. But Cats does. So you can create a Monad in Scala with the necessary boiler plate, e.g. traits and implicits cleverly used, or you can use cats which provides a monad trait out of the box. As a comparison, Haskel provides monads as part of the language. Regarding your specific question, an Option can be represented as a monad because it has a flatMap method and a unit method (wrapping a value in a Some or a Future, for example).

What are the differences between mapcat in Clojure and flatMap in Scala in terms of what they operate on?

I understand the equivalent to flatMap in Scala is mapcat in Clojure.
I have an inkling that mapcat in clojure only works with sequences, unlike flatMap in Scala which is more flexible.
My question is - what are the differences between mapcat in Clojure and flatMap in Scala in terms of what they operate on?
Assumptions:
I understand that Scala has a rich type system and Clojure has optional typing - I'm interested to know if the is a limitation in the parameters that mapcat accepts that make it only have a subset of flatMaps functionality.
I know a little about Scala but it seems to me flatMap is the Scala bind function in a monad and mapcat is a possible implementation of the bind function for the sequence monad in Clojure. So they are the same for sequences.
But Scala for example has a flatMap function for Futures: it takes a future and a mapping function and returns a future that will complete after input future completes. This operation doesn't seem to be a simple mapcat in Clojure. It may be realized this way instead
(defn flat-map [f mv] (mapcat (fn [v] (future (f #v))) mv))
So, no. They are not the same, neither in terms of what they operate on. In Scala flatMap is the common name for different functions and for example Futures' flatMap coordinates input and output futures. A simple mapcat in Clojure won't work because it won't return a future.
They seem very similar and appear to work on the same kind of things. From looking at the documentation and examples I can't see a functional difference.
mapcat works on sequences, and just about every clojure data type can be a sequence. If you pass something that is not already a seq to mapcat it will call seq on it automatically, so in practice you can pass just about all clojure values to mapcat. If you want to iterate over a tree you would need to call prewalk or postwalk to specify the traversal order.
In the standard Scala library: Responder, Future, Parser, ControlContext. None of them are sequences or particularly sequence-like. There is also a slight variation in ParseResult.
The real difference is that flatMap is polymorphic on the type, and mapcat isn't. So any type can decide to provide a "flatMap" like behaviour. That's how you get things like Futures being flatMapable.
In Clojure, mapcat is specific to the seqable type. Any seqable can be coerced into a sequence, and all sequence can be mapped and concatenated. The mapcat implementation will check if the input is seqable, if so, it will call seq on it to coerce it to a sequence, and then it will map and cat that sequence and give you back a sequence. You don't get back a result of the original type.
In Scala, if you implement IterableLike trait (I think that's the right interface), you get the default flatMap implementation which is a bit like the Clojure one minus the coercion to sequence. But, many types also provide a custom implementation of flatMap, making it generic in that way.

What are the main differences between Scala and Frege (in programming paradigms)?

Scala and Frege are both typed functional languages that target JVM.
Frege is closer to Haskell, Scala has a more independent history.
But if we don't look at syntactic differences, what are the differences in the allowed programming techniques, styles, concepts between the two?
IMHO both are really good languages but with respect to paradigms, Scala does OO better than Frege but Frege does functional better than Scala. With respect to differences, it comes down to mostly Haskell vs Scala since Frege is (or almost, see differences between Haskell and Frege here) Haskell for the JVM.
Frege's type inference is global so we don't have to annotate types as often as we do in Scala (local inference).
In Frege, modules are just namespaces for types and functions whereas Scala has better module system. http://2013.flatmap.no/spiewak.html
In Frege, functions are curried by default so there is no need for additional constructs for partial function application. Same goes for partial type constructor application.
In Frege, there is no def vs val and everything is function. Hence functions are more first-class than Scala.
Frege has no sub-typing but the type system figures out the sub typing on native calls. For example, you can pass an ArrayList to a function which requires a Java List.
Since there is no subtyping, in Frege we cannot extend a Java class or implement an interface as of now (might be supported in future) so we need to have a Java class which would extend/implement but the method implementations would be passed from Frege as functions.
From Scala, it is easy to call Java but in Frege, a Java class/method must be declared (Just the type and purity annotations) before use. For example, to use Java's LinkedList,
data LinkedList a = native java.util.LinkedList where
native add :: Mutable s (LinkedList a) -> a -> ST s Bool
native get :: Mutable s (LinkedList a) -> Int -> ST s (Maybe a) throws
IndexOutOfBoundsException
native new :: () -> STMutable s (LinkedList a)
Here since the functions mutate the object, they must be in ST monad. Also note that here Frege also handles null returned from the get method since it is annotated with Maybe type. The only way null can get through to your Frege program is through native interface since Frege doesn't have a notion of null.
Another example:
pure native floor Math.floor :: Double -> Double
which states that the function is pure and hence the signature directly reflects the original Java signature without IO or ST.
Frege has no variables as in Scala's var and the side effects
are more explicit through types. (Just no null, no var and explicit side effects make Frege more interesting, atleast for me. In a sense, Frege, just as Haskell, is a "fine imperative programming language", for the JVM!)
Being a Haskell dialect, Frege is more natural towards Functors, Applicatives, Monads and other functional "patterns" and has those in it's standard library whereas in Scala, you might need Scalaz.
Frege is lazy by default but strictness can be enabled where necessary through ! whereas Scala is strict by default but has lazy keyword for lazy evaluation.
Nevertheless, being JVM languages, one language can benefit from other. I once ported an Akka example to Frege. In the end, it comes down to strictness, purity, functional, OO and type inference and how much they matter to you.
Apart from syntactical issues, the biggest difference is in the type system and the execution model.
As #senia already pointed out, scala is strict and not pure, which does not mean that you can't write pure functions (you can do that in C, too), just that the compiler won't enforce it.
Frege, OTOH is lazy and pure, which means that all impure effects are forced to live in the ST or IO monad. The type system is essential that of Haskell 2010, with type classes and additional higher rank function types. Type inference works program wide, the only exception are functions with higher rank types, where at least the polymorphic argument must be annotated. Here is an example:
both f xs ys = (f xs, f ys)
For this function, the compiler infers the type:
both :: (α->β) -> α -> α -> (β, β)
Note that both xsand ysget the same type, because of the application of f.
But now lets say we want use a polymorphic list function that we can use with differently typed xs and ys. For example, we want to write:
both reverse [1,2,3] ['a' .. 'z']
As it stands, this application would be in error, because the two lists have different element types and hence different types. So the compiler would refuse the character list.
Fortunately, we can tell the compiler more precisly what we want with a type annotation:
both :: (forall e.[e] -> [e]) -> [a] -> [b] -> ([a], [b])
This tells the following: we will pass to both a function that does some list transformation but doesn't care about the list element type. Then we pass 2 lists with possibly different element types. And we get a tuple with our transformed lists back.
Note that the code of both needs not to be changed.
Another way to achieve the same would be to write:
both (f :: forall e.[e]->[e]) xs ys = (f xs, f ys)
and the type checker infers the rest, namely that xs and ys must be lists, but can have different element types.
Scalas type system fully (to my knowledge) supports OO. While Frege supports it only partially with regard to types imported for Java, but does not support definition of own OO-like types.
Hence, both languages support functional programming in a JVM environment, although in completly different niches. A third niche is the dynamically typed one, where Clojure is king in the JVM world.
Maybe it's off topic, but Scala can be used to develop Android applications (*), but Frege hasn't been successfully used for that, yet.(**) IIRC, it's because interop with existing Java libraries is much easier in Scala than in Frege, among other issues.
(*) Caveat emptor. I've only done small, example programs myself.
(**) Frege/Java mixes have been used for Android applications, but Frege-only applications are still not available, AFAIK.