Jas Jas - 1 month ago 6
Scala Question

in insufficiently-polymorphic why are there less ways to implement `List a -> List a -> List a` then `List Char -> List Char -> List Char`

in insufficiently-polymorphic

the author says about:

def foo[A](fst: List[A], snd: List[A]): List[A]



There are fewer ways we can implement the function. In particular, we
can’t just hard-code some elements in a list, because we have no
ability to manufacture values of an arbitrary type.


I did not understand this, because also in the
[Char]
version we had no ability to manufacture values of an arbitrary type we had to have them of type
[Char]
so why are there less ways to implement this?

Lee Lee
Answer

In the generic version you know that the output list can only contain some arrangement of the elements contained in fst and snd since there is no way to construct new values of some arbitrary type A. In contrast, if you know the output type is Char you can e.g.

def foo(fst: List[Char], snd: List[Char]) = List('a', 'b', 'c')

In addition you cannot use the values contained in the input lists to make decisions which affect the output, since you don't know what they are. You can do this if you know the input type e.g.

def foo(fst: List[Char], snd: List[Char]) = fst match {
    case Nil => snd
    case 'a'::fs => snd
    case _ => fst
}