Take the 2-minute tour ×

The Scala collections api has some pretty interesting properties and I'm wondering how one would implement it in Haskell; or if it's even possible (or a good idea in general). I'm a bit of a haskell newbie so I'd like to hear your thoughts.

The scala map definition looks like this:

def map[B, That](f: A => B)(implicit bf: CanBuildFrom[Repr, B, That]): That

An interesting feature of this API is that if you map over a string and your map function returns a character, the result will be of type string (and not a list of characters).

share|improve this question
In Haskell, a string is a list of characters. (This doesn't answer your question in the general case, but I thought it was worth nothing.) –  mipadi Jan 13 '11 at 22:03
A good bit of the Scala (2.8) API library resolves around dealing with existing types and how to play nicely with them. The two biggest examples are likely String and arrays. Without said existing type issues, I believe much of the implicit builders is unneeded (they are designed to allow "collapsing" to a container of the same type as the input). –  user166390 Jan 13 '11 at 22:08
pst, not so. See this example from Martin Odersky (stackoverflow.com/questions/1722726/…) where the issue is that BitSet has a very efficient representation that is only compatible with ints but we would still like to be able to treat it like any Set with map etc. If it was just an "existing types" issue then BitSet could be discarded. –  James Iry Jan 13 '11 at 22:35
@James, I was going to say the same thing, but about Maps. Map(1->2, 3->4).map{ (k,v) => k+v } results in a Seq, but Map(1->2, 3->4).map{ (k,v) => (k+1,v+1) } results in a Map because of CanBuildFrom. –  Ken Bloom Jan 14 '11 at 1:26
The implicit CanBuildFrom is, as far as I can tell, a Scala-style type class. In Haskell you could have a multi-parameter type class (I think that might be implementation-dependent,) so you can do the same thing. –  MJP Jan 14 '11 at 9:27
show 1 more comment

2 Answers

up vote 6 down vote accepted

We have something roughly as general as the Scala API. It's called Foldable.

class Foldable t where
  fold :: Monoid m => t m -> m


share|improve this answer
By using foldMap the resulting collection (the equivalent of That from Scala), depends on which monoid is chosen? Are all collections monoids? –  David Powell Jan 14 '11 at 6:09
@Grazer, nearly all collections are monoids. In particular all collections provided by the containers package have Monoid instances. The biggest subset of non-monoid collections that comes to mind are collections that must contain at least one element, because a monoid requires an identity (e.g. empty) collection. –  John L Jan 14 '11 at 12:31
add comment

I want to say this map function in Scala is really closer to this from Haskell:


Where the list type is just another Functor.

share|improve this answer
add comment

Your Answer


