[Haskell-cafe] constant functions
nowgate at yahoo.com
Wed Dec 27 23:02:59 EST 2006
Thanks Brian. I think these signatures are starting to
make sense. And I didn't know "_" (don't care) could
be used like that. I'm liking Haskell more and more.
--- Bryan Burgers <bryan.burgers at gmail.com> wrote:
> > I'm trying to learn Haskell and translating some
> > functions as exercises.
> > How would I write a Haskell function named ALWAYS
> > behaves like this:
> > one = always 1
> > bozo = always "clown"
> > > map one [2,3,4,5,6]
> > [1,1,1,1,1]
> > > one 62
> > 1
> > > map bozo [2,3,4,5,6]
> > ["clown","clown" ,"clown", "clown"," clown"]
> > > bozo 62
> > "clown"
> > i.e. ALWAYS returns a function with a single
> > that is ignored, returning instead the value given
> > ALWAYS when the function was created.
> > This is what I've been trying:
> > always :: (a -> a) -> a -> a
> > always x = (\y -> x)
> > one = always 1
> > Michael
> First, you want 'one' to take an integer and return
> 1. So,
> > one :: Integer -> Integer
> since one = always 1, then
> > always 1 :: Integer -> Integer
> So, 'always' takes an Integer and returns an Integer
> -> Integer
> > always :: Integer -> (Integer -> Integer)
> But that's the same as
> > always :: Integer -> Integer -> Integer
> You actually have the implementation correct, you
> just didn't have the
> right type signature.
> > always first = (\second -> first)
> Of course, neither of these implementations need to
> be tied to
> Integers; they can be polymorphic. So, we end up
> always :: a -> b -> a -- no reason the second
> parameter has to be the
> same type as the first, so use 'b' instead of 'a'.
> always first = (\_ -> first) -- replace 'second'
> with '_', because
> we don't need to bind anything to the second
> Does that makes sense?
> Bryan Burgers
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
More information about the Haskell-Cafe