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

Jason Dagit dagit at codersbase.com
Mon Jun 1 21:02:09 EDT 2009

Hi Dan,

On Mon, Jun 1, 2009 at 8:39 PM, Dan Cook <danielkcook at gmail.com> wrote:

> Hi,
> (Relatively new to Haskell here ..)
> So I have the following:
> data MyVal =  Atom String
>                        | Bool Bool
> And I want to do something like this
> check :: (Bool -> MyVal) -> MyVal -> True
> check f (f x) = True
> check _ _ = False

You may be confusing yourself here on one point.  The type 'Bool' is already
defined by the prelude, but the data constructor is not.  So you are able to
create a data constructor for MyVal that is called "Bool" and contains a
Bool.  I think this distinction is leading to the next probem I see.  Type
signatures have to contain types and not values in Haskell.  'True' is a
value so it can't be placed in the type signature.  The type of True is
Bool.  So I think you meant to ask about:
check :: (Bool -> MyVal) -> MyVal -> Bool

Now if you define this function the first parameter can be any function Bool
-> MyVal, not just the data constructors of MyVal.  Also, the type of Atom
:: String -> MyVal so you can't even pass it to 'check'.

> What that means is I want to pass a MyVal constructor and a MyVal, and
> return True if the second argument was constructed with the first.  More
> generally, I'd like to be able to do
> genCheck :: (* -> MyVal) -> MyVal -> True
> genCheck f (f x) = True
> genCheck _ _ = False
> So that I can pass in _any_ MyVal constructor and let the function just
> check if the second argument was constructed with the first, without caring
> which constructor it is.

This strikes me as a job for template haskell, but the use of TH is beyond
what I can explain :)

> What is the preferred way to do this, since neither of those functions
> compile?

My preferred way, is just to define isAtom and isBool both with type MyVal
-> Bool and use them where I need them.  There are a number of tools to
generate such things like DrIFT, TH, and maybe some others?

I hope that helps,
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://www.haskell.org/pipermail/haskell-cafe/attachments/20090601/5c6b3080/attachment.html

More information about the Haskell-Cafe mailing list