Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Learning Haskell: where-clause variable x, where does it come from?

Tags:

haskell

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  
like image 611
rik_mg Avatar asked Aug 18 '19 11:08

rik_mg


1 Answers

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.

like image 195
Robin Zigmond Avatar answered Nov 14 '22 10:11

Robin Zigmond