[Haskell-cafe] constant functions
Donald Bruce Stewart
dons at cse.unsw.edu.au
Wed Dec 27 22:01:21 EST 2006
nowgate:
> I'm trying to learn Haskell and translating some Lisp
> functions as exercises.
>
> How would I write a Haskell function named ALWAYS that
> 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 parameter
> that is ignored, returning instead the value given to
> 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"
[1,1,1]
*Main> let bozo = always "clown"
*Main> bozo "haskell"
["clown","clown","clown","clown","clown","clown","clown"]
Now handle the non-list case:
alwaysAtom :: a -> b -> a
alwaysAtom a b = a
*Main> let one = alwaysAtom 1
*Main> one 'x'
1
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
More information about the Haskell-Cafe
mailing list