[Haskell-beginners] Re: let indenting problems
apfelmus at quantentunnel.de
Tue Mar 3 06:20:45 EST 2009
> Heinrich Apfelmus <apfelmus <at> quantentunnel.de> writes:
>> How about
>> import Data.Ord (comparing)
>> mySort = sortBy (comparing length)
> I just finished chap. 3 of Real World Haskell, which doesn't
> even imports. It took me hours to figure out how to
> access sortBy. The book hasn't introduced "comparing", yet.
It's a handy little function for exactly this sort of thing. It's defined as
comparing p x y = compare (p x) (p y)
>> or at least
>> mySort = sortBy myCompare
>> myCompare x y = compare (length x) (length y)
> Very nice. The book mentioned the compare function in
> chap. 2.
> I have a question about that code: how come you
> don't have to specify a parameter for mySort, for example:
> mySort xs = ...
> And doesn't sortBy require two arguments?
> sortBy :: (a -> a -> Ordering) -> [a] -> [a]
> (1) (2)
> How come you can write it with only one argument?
You can supply arguments one at a time, this is called "currying". In
other words, the expression sortBy myCompare is created by supplying
one argument to sortBy and thus has one argument remaining. More
specifically, it has the type
sortBy myCompare :: [[a]] -> [[a]]
Furthermore, we can simply set
mySort = sortBy myCompare
and the left hand side will be a function with one argument just like
the right hand side is.
> Finally, I'm wondering if anyone can explain why my
> let examples failed?
Your use of let in conjunction with where was not syntactically
correct. While both are used for declaring new things, let is an
expression while where is a declaration, these two don't mix.
In particular, let must always have the form
x = ...
y = ...
while where is used like this
foo x y
| ... = expr1
| ... = expr2
a = ...
b = ...
let ... in where ...
let ... in | ...
do not exist, there is no expression after the in . I suggest
consulting a syntax reference for Haskell or using where only for the
More information about the Beginners