[Haskell-cafe] Checking a value against a passed-in constructor?

Ryan Ingram ryani.spam at gmail.com
Tue Jun 2 15:11:53 EDT 2009


On Tue, Jun 2, 2009 at 3:50 AM, Dan <danielkcook at gmail.com> wrote:
> You hit the nail on the head.  "Why I am doing this" is because of
> boilerplate. Boilerplate gives me rashes and bulbous spots on the nose.
>
> Consider the following Ruby code:
>
>        def check(zeClass, zeValue)
>                zeValue.is_a? zeClass
>        end
>
> This does not require a new function for every class defined in Ruby.
> (To be fair, though, the class of a Ruby object tells you precious
> little, compared to a Haskell type constructor).
>
> I figured there would be a clever Haskell idiom that would give me a
> similarly concise route. Does it really require Template Haskell? I can
> barely parse regular Haskell as it is..

So the question is, why do you need to know if x is an Atom or a Bool?
 The Haskell idiom is to pattern match and just do what you want with
the data:

f (Atom s) = ...
f (Bool b) = ...

instead of

f x = if isAtom x then ... atomData x ... else ... boolData x ...

Alternatively, you can define a fold[1] once:

myval :: MyVal -> (Bool -> a) -> (String -> a) -> a
myval (Bool b) bool atom = bool b
myval (Atom s) bool atom = atom s

f x = myval bool atom where
   bool b = ...
   atom s = ...

This is a small amount of boilerplate that you write once for each
type; it's possible to automate it with TH, but usually it's not worth
it, in my opinion.

Coming from Ruby (the same route I took to get to Haskell!), you
should be aware that Haskell does have somewhat more "boilerplate"
than Ruby, but it has its benefits as well.  I am a convert to the
Church of Purity and Type-Safety :)  And you can use type classes for
many metaprogramming tasks.

  -- ryan

[1] "fold" here is the general term for this type of function.  Examples are
foldr: http://haskell.org/ghc/docs/latest/html/libraries/base/src/GHC-Base.html#foldr
maybe: http://haskell.org/ghc/docs/latest/html/libraries/base/src/Data-Maybe.html#maybe
either: http://haskell.org/ghc/docs/latest/html/libraries/base/src/Data-Either.html#either


More information about the Haskell-Cafe mailing list