[Haskell-begin] some basic syntax questions
Felipe Lessa
felipe.lessa at gmail.com
Fri Jul 25 15:53:21 EDT 2008
On Fri, Jul 25, 2008 at 4:45 PM, Anatoly Vorobey <avorobey at gmail.com> wrote:
> 1. I initially tried putStrLn("Hello, " ++ show $ sumIt args), but that
> didn't compile. Why not?
You see,
Prelude> :i (++)
(++) :: [a] -> [a] -> [a] -- Defined in GHC.Base
infixr 5 ++
Prelude> :i ($)
($) :: (a -> b) -> a -> b -- Defined in GHC.Base
infixr 0 $
so
"Hello, " ++ show $ sumIt args
is parsed as
("Hello, " ++ show) $ sumIt args
which is an obvious error.
> 2. I initially tried
>
> where sumIt = sum $ map read
>
> (the "point-free" style, I believe it's called?) but that didn't compile.
> Why not? A friend suggested
>
> where sumIt = sum . map read
>
> and that does work; I guess my real problem, then, is that I don't really
> understand the difference
> between the two and why the former doesn't work.
It helps to see the types and the definitions
($) :: (a -> b) -> a -> b
f $ x = f x
(.) :: (b -> c) -> (a -> b) -> (a -> c)
f . g = \x -> f (g x)
so ($) applies an argument, while (.) composes functions. For example,
sumIt x = sum (map read x)
so
sumIt x = sum $ map read x
by ($)'s definition. On the other hand
sum $ map read is sum (map read) [by ($)'s definition again]
which is, again, a mistake. However, we may write sumIt as
sumIt = \x -> sum (map read x)
so it becames clear that
sumIt = sum . map read
Did I help at all? =)
--
Felipe.
More information about the Beginners
mailing list