How does the Haskell compiler handle the where statement?

In the next function, I wonder if the compiler is sufficiently equipped to work out what xwill remain constant, or will it calculate the list title for each item in the list? (I use GHC)

allSame :: Eq a => [a] -> Bool 
allSame xs = all (==x) xs  where x = head xs
+3
source share
2 answers

The semantics of “where” in the GHC is that a single closure will be allocated for “x” and is available for all uses. A new closure will be created for the function (== 'x'), and the optimizer will pop up so that it is generated only once per bypass.

, , Core (, ghc-core). GHC :

M.allSame a eq xs =
    all
      (let 
         ds =
           case xs of 
             []   -> error "bad head"
             x : _-> x
            in
          \y -> x == y
         ) xs

, , , .

+11

, Haskell , : x where -clause. , x all.

, myall, , all (==x), . , , , , .

Edit:

: myall .

myall x [] = [x]
myall x xs =  x:(myall x (tail xs))

test xs = myall (x) xs where x = head xs

test [1,2,3], , [1,1,1,1], .. x 1, myall.

0

Source: https://habr.com/ru/post/1761861/


All Articles