Steve Frampton wrote:

>Okay, I'm [damn] confused regarding type-casting in Haskell.

Because there isn't any?

>I'm trying
>to write a function that accepts an integer and then returns a set (in
>this case, a set of characters).
>
>I'm having a lot of problems with "Declared type too general", "Type error
>in application", etc. depending on what I try.
>
>My function looks sort of like this:
>
>  foo :: Int -> [a]
>  foo 0 = []
>  foo x = ['1'] ++ foo(x - 1)
>
>I would expect that I'd end up with a set of '1111's depending on how
>large a value I pass to 'foo'.  However, I can't seem to make the
>interpreter happy, no matter what I try (sounds like an ex-gf of mine).

Well, the example you give doesn't make much sense, since the returned list
will always be a list of characters; thus the supplied signature Int -> [a]
is indeed too general. Int -> [Char] would be correct.

If the signature Int -> [a] represents what you really want, then the code
is wrong, and I'm not sure what you're trying to do. You want a list N
elements long, obviously, but what are the members of the list? If you want
the type of the list members to be different depending on how you use the
function, then the function needs an argument that tells it what type (and
what value of that type) to use, like this:

foo :: Int -> a -> [a]
foo 0 _ = []
foo x a = a : foo (x - 1) a

With this, evaluating foo 3 '1' results in "111" :: [Char], and evaluating
foo 3 1 results in [1, 1, 1] :: [Int], which makes sense and sounds like it
might approach what you're looking for.

This function could be further improved by making it tail-recursive, but
that's not quite germane to your question.

>I thought maybe I need some kind of type-cast ala C, but I'm not really
>sure what needs to be put there.

Absolutely not. It sounds like you're thinking you can call foo, have it
generate a list of unknown type but known length, and then assign a type
afterwards. You can't do that.

Craig




Reply via email to