Function definition with / without lambdas

What difference does it make if I define a function with or without a lambda expression when compiling a module with GHC

f :: A -> B
f = \x -> ...

vs.

f :: A -> B
f x = ...

I think I saw that it helps the compiler to embed the function, but cannot affect my code if I switch from the first to the second version.

I’m trying to understand someone’s code and get away from reasoning about why this function is defined in the first and not the second way.

+4
source share
2 answers

Firstly, the second form is more flexible (it allows you to match patterns, with other points below for alternative cases).

, ... where. ,

f = \x -> someCalculation x y
 where y = expensiveConstCalculation

,

f x = someCalculation x y
 where y = expensiveConstCalculation

, y , f . y :

  • f , f , . , y , someCalculation f. , , , , , , y .
  • f , , . , , , . map f longList, y , .

, . , , GHC , , , , . .

+5

, Core:

f1 :: Int -> Int
f1 = \x -> x + 2
{-# NOINLINE f1 #-}

f2 :: Int -> Int
f2 x = x + 2
{-# NOINLINE f2 #-}

, ghc test.hs -ddump-simpl. :

f1_rjG :: Int -> Int
[GblId, Arity=1, Str=DmdType]
f1_rjG =
  \ (x_alH :: Int) -> + @ Int GHC.Num.$fNumInt x_alH (GHC.Types.I# 2)

f2_rlx :: Int -> Int
[GblId, Arity=1, Str=DmdType]
f2_rlx =
  \ (x_amG :: Int) -> + @ Int GHC.Num.$fNumInt x_amG (GHC.Types.I# 2)

, , : .


, , , .

+8

All Articles