[Haskell-cafe] constant functions
nowgate at yahoo.com
Wed Dec 27 23:22:28 EST 2006
I think you misunderstood what I was asking. There's
not two cases. Maybe I'm not saying it sufficiently
well but the function ALWAYS just returns a function
that always returns the original argument to ALWAYS no
matter what else you give the resulting function.
when one is define as follows
one = always 1
> one 4
> one "abc"
> one (2,3)
> one [0,4,8,2]
> map one ["one","two","three"]
The mapping example is just an alternative way of
illustrating the functionality. No matter what the
defined function is given it always gives back the
original value give to ALWAYS.
--- Donald Bruce Stewart <dons at cse.unsw.edu.au> 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
> So there are two cases you want to handle:
> * return a list, if the argument is a list
> * return a single value, if the argument is a
> single value.
> We can write thes functions separately:
> alwayList :: a -> [b] -> [a]
> alwayList n xs = map (const n) xs
> *Main> let one = always 1
> *Main> one "foo"
> *Main> let bozo = always "clown"
> *Main> bozo "haskell"
> Now handle the non-list case:
> alwaysAtom :: a -> b -> a
> alwaysAtom a b = a
> *Main> let one = alwaysAtom 1
> *Main> one 'x'
> Unifying these two under a common type class is left
> as an exercise ;)
> I guess the type signature for such a class would be
> something like:
> class Const a b a' | b -> a', a' -> a where
> Something like that.
> -- Don
Do You Yahoo!?
Tired of spam? Yahoo! Mail has the best spam protection around
More information about the Haskell-Cafe