[Haskell-beginners] Polymorphism question from an OO-speaking newbie

Joel Neely joel.neely at gmail.com
Mon May 4 11:34:09 EDT 2009


Short version: Is it possible/reasonable to define a single function
that accepts a single string or a list of strings (in which case it
maps the single-string "flavor" over the list)?

Longer version: Thus far I know that Haskell allows me to define a
function on a single string, then define another function that maps
the first one across a list of strings, as in:

    *Main> let quote1 s = "\"" ++ s ++ "\""

    *Main> "Quux said " ++ quote1 "foo" ++ " loudly"
    "Quux said \"foo\" loudly"

    *Main> let quote = map quote1

    *Main> quote ["foo", "baz", "bletch"]
    ["\"foo\"","\"baz\"","\"bletch\""]

(BTW, is it standard terminology to say that quote lifts quote1 to lists?)

In the above I have different names for the two functions. OO
languages such as Java allow me to overload quote to accept either
String or List<String> (and return the same type). AFAICT, Haskell's
parametric polymorphism allows me to define functions (e.g. length)
which deal with "listness" concepts indifferent to the type contained
by the list.

Am I missing something, or should I admit to OO wrongheadedness and
accept that my inability to write a single declaration unifying:

    quote :: String -> String
    quote :: [String] -> [String]

is an emphatic clue that I should change my expectations?

Thanks in advance for any enlightenment shed my way!

-jn-

-- 
Beauty of style and harmony and grace and good rhythm depend on
simplicity. - Plato


More information about the Beginners mailing list