The composition of the function and its presentation

Interesting:

1) the following functions are exactly the same:

inc = (+1)
double = (*2)

func1 = double . inc
func2 x = double $ inc x
func3 x = double (inc x)
func4 = \x -> double (inc x)

2) why compilation func5?

func5 = double $ inc        -- doesn't work
+4
source share
4 answers

Are these functions the same?

Actually, no! There are some very subtle differences. First of all, read about the terrible restriction of monomorphism . In short, class-polymorphic functions are defined differently by default if they are "explicitly" functions or not. In your code, this difference will not be shown because it incand doubleare not "clearly" and therefore functions defined monomorphic types. But if we make a small change:

inc, double :: Num a => a -> a
inc = (+1)
double = (*2)

func1 = double . inc
func2 x = double $ inc x
func3 x = double (inc x)
func4 = \x -> double (inc x)

ghci , func1 func4 - "" - :

*Main> :t func1
func1 :: Integer -> Integer
*Main> :t func4
func4 :: Integer -> Integer

func2 func3 :

*Main> :t func2
func2 :: Num a => a -> a
*Main> :t func3
func3 :: Num a => a -> a

, ( ) . (.) ($) , , func1 func2 , . , , func1 3 :

func1 3
= {- definition of func1 -}
(double . inc) 3
= {- definition of (.) -}
(\f g x -> f (g x)) double inc 3
= {- beta reduction -}
(\g x -> double (g x)) inc 3
= {- beta reduction -}
(\x -> double (inc x)) 3

, , func4 3, :

func3 3
= {- definition of func3 -}
(\x -> double (inc x)) 3

. , GHC (.), ($) , ; , , , , ( ).

func5?

! , . , func5 3. , "".

func5 3
= {- definition of func5 -}
(double $ inc) 3
= {- definition of ($) -}
(\f x -> f x) double inc 3
= {- beta reduction -}
(\x -> double x) inc 3
= {- beta reduction -}
double inc 3
= {- definition of double -}
(\x -> x*2) inc 3
= {- beta reduction -}
(inc * 2) 3
= {- definition of inc -}
((\x -> x+1) * 2) 3

. , ( , "" !), "" - , . ! "" - , , ..

, , double , , , inc - , . , : , , - .

+15

1) . .

2) , func5 , :

func5

-- Definition of `func5`
= double $ inc

-- Definition of `($)`
= double inc

-- Definition of `double`
= 2 * inc

-- Definition of `inc`
= 2 * (1 +)

, (1 +) - , .

+7

.


double inc. , inc .

double $ inc
-- is the same as
double inc

, :

inc :: Integer -> Integer
double :: Integer -> Integer

double Integer, Integer -> Integer.

, Haskell, .

+4

$ ( ) . ( ). , ghci:

>:t ($)
($) :: (a -> b) -> a -> b

:t (.)
(.) :: (b -> c) -> (a -> b) -> a -> c

You can always replace $with parentheses. Therefore func2, func5it can be rewritten as:

func2 x = double (inc x)
func5 = double (inc)

But it doubleexpects a type value Num a => a, and you pass it a type value Num a => a -> a, so it doesn't work.

Read more about $ here and about ..

+3
source

All Articles