I am learning Haskell and this will be my first post.
In the great online book http://learnyouahaskell.com/syntax-in-functions#where there is the example largestDivisble
. In the where-clause the variable x
is introduced but where does it come from? Untill now the variables where bounded in the pattern-matching part of the function body.
As I now interpret it:
the part where p x
declares the function p
and the application of some variable x
. In the body filter p [some-list]
, the some-list stands for x
.
I think this is all a bit fuzzy. Can someone help me out with a explanation of this piece of code?
largestDivisible :: (Integral a) => a
largestDivisible = head (filter p [100000,99999..])
where p x = x `mod` 3829 == 0
x
there is just the function argument. It's entirely local to the definition of p
.
You could have defined it as a separate, top-level function, like this:
p :: (Integral a) => a -> Bool
p x = x `mod` 3829 == 0
and note that the type signature here isn't required, it's just good practice to include it for a top level function. The definition of p
in the where
clause is identical, including x
being a local name for the function argument. The only difference between the two is that a function defined in a where
clause is local to the definition that includes that clause, and can't be accessed outside.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With