[Haskell-cafe] Haskell and the Software design process
ajb at spamcop.net
ajb at spamcop.net
Mon May 3 02:35:06 EDT 2010
G'day all.
Quoting aditya siram <aditya.siram at gmail.com>:
> I'm a little confused about this too. I've seen many functions defined like:
> f x = (\s -> ...)
> which is a partial function because it returns a function and is the same as:
> f x s = ...
>
> Off the top of my head the State monad makes extensive use if this
> style. Is this bad?
It's not inherently bad style.
In the State/Reader monads, the passed-in parameter is part of the type:
type State s a = s -> (s,a)
f :: Foo -> State s a
Since f has only one argument according to its type signature, it
makes sense to give it only argument in its rules as well:
f x = \s -> ...
This re-enforces the fact that s is an implementation detail of State.
It is an error in Haskell to have multiple rules for a function with
different arities. So this, for example, is illegal:
f True = length
f False [] = 3
f False (_:_) = 2
If there were a good reason for writing the first rule in a point-free
manner, it would be perfectly reasonable to rewrite this using an
explicit lambda.
There are also performance issues which may be relevant. GHC doesn't
break up lambdas to do let-floating, so if that's what you want, you
may need to express it manually:
data TreeSet a
= Null
| Singleton a
| Doubleton a a
| Branch a TreeSet TreeSet
elem :: (Ord a) => TreeSet a -> a -> Bool
elem Null
= \p -> False
elem (Singleton p1)
= \p -> p == p1
elem (Doubleton p1 p2)
= \p -> p == p1 || p == p2
elem (Branch p' l r)
= let elem_l = elem l
elem_r = elem r
in \p -> if p < p' then elem_l p else elem_r p
Like all situations where you've got more than one way to express
something, which one you pick depends on what you're trying to say.
Cheers,
Andrew Bromage
More information about the Haskell-Cafe
mailing list