Function application in Haskell - function

OK, it's been a long day and my brain may not function at Haskell level, but I just cannot understand one example from 'Learn You a Haskell'.
The section is called Function Application with $, and there is example of how $ may be defined:
($) :: (a -> b) -> a -> b
f $ x = f x
So far everything is clear. I understand all examples in the section, except for the last one:
ghci> map ($ 3) [(4+), (10*), (^2), sqrt]
[7.0,30.0,9.0,1.7320508075688772]
Here we map ($ 3) across list of functions and get result of application of those functions to 3. But how is this possible?
From the first code snippet it's clear that first argument is a function, we can even write:
*Main> ($) sqrt 4
2.0
Now ($ 3) is a partial application of function $, but 3 goes on function's position! So 3 is supposed to be a function or what?
There is another mystery: what the heck is (4+)? I know that (+4) is a partial application of function +, so (4+) should be partial application of function 4? Nonsense. What sort of trick works here?

($ 3) and (+ 4) aren't partial applications - they're operator sections. A partial application would look like (($) 3) or ((+) 4).
An operator section of the form (? x) (where ? stands for an arbitrary infix operator) binds the right operand of the operator, i.e. it is equivalent to \y -> y ? x. Likewise the operator section (x ?) binds the left operand and is thus equivalent to partial application.

I think what's tripping you up is operator sections. These let you partially apply an operator with either one of its arguments, so you can have the operators (+4) and (4+), where 4 is the the second then the first argument to + respectively. A more clear example might be ("Hello" ++) versus (++ "world"), the former prepends "Hello" onto the front of a string, while the latter appends "world" onto the end of a string.
This is contrasted with using operators in prefix form with just parens around it. In this form, the following are equivalent:
> let join = (++)
> join "Hello, " "world"
"Hello, world"
> (++) "Hello, " "world"
"Hello, world"
In prefix form, you treat the operator as a normal function and it accepts its first then second argument in order. In operator sections, it matters which side of the operator the argument is on.
So in your example, you have the partial application of ($ 3), you can reduce it as
map ($ 3) [(4+), (10*), (^2), sqrt]
[($ 3) (4+), ($ 3) (10 *), ($ 3) (^ 2), ($ 3) sqrt]
[4 + 3, 10 * 3, 3 ^ 2, sqrt 3]
[7.0, 30.0, 9.0, 1.7320508075688772]

You are getting confused with sections. A good way to grasp the concept of sections is playing with an example:
(<^>) :: Int -> Float -> Int
a <^> b = a
The above function is an useless function which returns the first parameter no matter what the second parameter is. But it accepts Int and then Float as input.
Now, because of sections you can apply with any one of their arguments:
λ> let a = (3 <^>)
λ> :t a
a :: Float -> Int
λ> let b = (<^> 3.0)
λ> :t b
b :: Int -> Int
See how the type of a and b are different because of sections.

Related

How is one implementation of the constant function equal to a version using a lambda?

I'm currently revising the chapter for the lambda (\) expressions in Haskell. Was just wondering if someone could please help explain how did this:
const :: a → b → a
const x _ = x (this part)
Get defined into this:
const :: a → (b → a)
const x = λ_ → x (how did it become like this?)
The signatures a -> b -> a and a -> (b -> a) are parsed exactly the same, much like the arithmetic expressions 1 - 2 - 3 and (1 - 2) - 3 are the same: the -> operator is right-associative, whereas the - operator is left associative, i.e. the parser effectively puts the parentheses in the right place if not explicitly specified. In other words, A -> B -> C is defined to be A -> (B -> C).
If we explicitly write a -> (b -> a), then we do this to put focus on the fact that we're dealing with curried functions, i.e. that we can accept the arguments one-by-one instead of all at once, but all multi-parameter functions in Haskell are curried anyway.
As for why const x _ = x and const x = \_ -> x are equivalent: well first, to be pedantic they're not equivalent, see bottom of this answer. But let's ignore that for now.
Both lambdas and (single) function clauses are just ways to define functions. Like,
sqPl1 :: Int -> Int
sqPl1 x = x^2 + 1
does the same as
sqPl1 = \x -> x^2 + 1
It's just a different syntax. Some would say the f x = ... notation is just syntactic sugar for binding x in a lambda, i.e. f = \x -> ..., because Haskell is based on lambda calculus and in lambda calculus lambdas are the only way to write functions. (That's a bit of an oversimplification though.)
I said they're not quite equivalent. I'm referring to two things here:
You can have local definitions whose scope outlasts a parameter binding. For example if I write
foo x y = ec * y
where ec = {- expensive computation depending on `x` -}
then ec will always be computed from scratch whenever foo is applied. However, if I write it as
foo x = \y -> ec * y
where ec = {- expensive computation depending on `x` -}
then I can partially apply foo to one argument, and the resulting single-argument function can be evaluated with many different y values without needing to compute ec again. For example map (foo 3) [0..90] would be faster with the lambda definition. (On the flip side, if the stored value takes up a lot of memory it may be preferrable to not keep it around; it depends.)
Haskell has a notion of constant applicative forms. It's a subtle topic that I won't go into here, but that can be affected by whether you write a function as a lambda or with clauses or expand arguments.

How does the recursive call work in this erlang function?

fun({0, M}) -> {M+1, M-2};
fun({N, M}) ->
{A, B} = fun({N-1, M+1}),
{B, A+1}.
so I am kinda unsure of what the A and B would be and how the next recursive call would be. let say 2,2
so it would be
f(2,2) -> {A,B} = fun({1,3}), {B,A+1}
f(1,3) -> {A,B} = fun({0,4}), {B,A+1}
f(0,4) -> {5,2}
but where does A and B go and do they change in each recursive call?
As a very basic explanation of "where is my variable", consider the countdown function in this example module:
-module(example).
-export([countdown/1]).
-spec countdown(non_neg_integer()) -> ok.
countdown(0) ->
io:format("Blastoff!~n");
countdown(N) when N > 0 ->
ok = io:format("Counting down in: ~w~n", [N]),
Next = N - 1,
countdown(Next).
If we hit the base case, which is 0, then we stop. The return value of the function overall is the atom ok (because that is the return value of a successful call to io:format/2).
If the input is greater than 0 then we match on the second clause, which means we assign N the sole input argument for this particular iteration. The next thing we do is make our output call. Then we assign Next to the value N - 1. Then we call the same function again (do a loop) using the value of Next in body of the the current call as the input argument.
The next iteration all the variables are totally new because this is a fresh execution context. The old N and Next no longer exist. In fact, they don't event exist on a stack anywhere because Erlang uses "tail call optimization" to maintain recursive tail calls in constant space, the same way most other languages would do an explicit for or while or do while or [insert form].
As Alexy points out, be careful about the token fun -- it is a keyword in Erlang, not a legal function name. It is the non-name of an anonymous function (also known as a lambda). In other words, unless you provide a label, the name of every anonymous function is just fun.
fun is also the keyword that is used to reference a function by label (to use as a value itself) instead of calling it. For example, countdown(10) calls the function above with an argument of 10. Referencing the function as fun countdown/1 returns the function itself as a value. That is, incidentally, why the function export declaration at the top of the module is written as -module([countdown/1]), because that is the explicit name of this function. Consider this:
1> c(example).
{ok,example}
2> example:countdown(2).
Counting down in: 2
Counting down in: 1
Blastoff!
ok
3> Countdown = fun example:countdown/1.
#Fun<example.countdown.1>
4> Countdown(2).
Counting down in: 2
Counting down in: 1
Blastoff!
ok
While I'm on the subject...
Erlang has very few keywords compared to most languages (and very little syntax, actually). Here is the list of reserved words:
after and andalso band begin bnot bor bsl bsr bxor case catch cond div end fun if let not of or orelse receive rem try when xor
You just need to go back up:
f({1, 3}) -> {A, B} = {5, 2}, {B, A+1} -> {2, 6}
f({2, 2}) -> {A, B} = {2, 6}, {B, A+1} -> {6, 3}
(note that fun is a keyword in Erlang and that f(N,M) is not the same as f({N,M}))
and do they change in each recursive call
Yes, as you can see.

Expand a function in Haskell

In my homework, we are given a regular expression. I have to return an e-NFA. I'm trying to build the delta function. So far I have:
module ConsENFA where
import Data.Set (Set, fromList, singleton, empty)
import RegEx
import ENFA
epsilon :: RegExp Char
epsilon = Symbol 'e'
deltaTest :: RegExp Char -> Int -> (Int -> Char -> Set Int)
deltaTest (Symbol sym) start = delta
where
delta :: Int -> Char -> Set Int
delta start sym = singleton (start + 1)
deltaTest (Star re) start = delta
where
delta :: Int -> Char -> Set Int
delta = deltaTest re (start + 1)
delta start epsilon = fromList[1, 3]
I got the error
ConsENFA.hs:19:9: error:
Conflicting definitions for `delta'
Bound at: ConsENFA.hs:19:9-13
ConsENFA.hs:20:9-13
which I assume means that I can't expand the pattern matching like that, I can't add more states.
I first define delta for a single label and then I add more definitions to the previously defined delta, but it's not working. What's the correct way to do it?
All definitions of a function must have the same arity, i.e., the same number of function arguments. You define delta in three lines:
The first line is a type signature.
The second line is a definition of delta with arity zero (no arguments to the left of the =)
The third line is another definition of delta with arity two (two arguments to the left of the =)
The two definitions have a different arity, so the compiler tells you there are conflicting definitions.
Ask yourself: What is the inteded behavior of delta? The compiler will look at the definitions of delta in the order they are defined, and choose the first one where a pattern match succeeds. Since there are no arguments in the first definition (and hence no patterns to match), it will always succeed and the second definition will never be called.

Number of functions in expression - SML

How many functions are present in this expression? :
'a -> 'a -> ('a*'a)
Also, how would you implement a function to return this type? I've created functions that have for example:
'a -> 'b -> ('a * b)
I created this by doing:
fun function x y = (x,y);
But I've tried using two x inputs and I get an error trying to output the first type expression.
Thanks for the help!
To be able to have two inputs of the same alpha type, I have to specify the type of both inputs to alpha.
E.g
fun function (x:'a) (y:'a) = (x, y);
==>
a' -> 'a -> (a' * 'a)
Assuming this is homework, I don't want to say too much. -> in a type expression represents a function. 'a -> 'a -> ('a * 'a) has two arrows, so 2 might be the answer for your first question, though I find that particular question obscure. An argument could be made that each fun defines exactly one function, which might happen to return a function for its output. Also, you ask "how many functions are present in the expression ... " but then give a string which literally has 0 functions in it (type descriptions describe functions but don't contain functions), so maybe the answer is 0.
If you want a natural example of int -> int -> int * int, you could implement the functiondivmod where divmod x y returns a tuple consisting of the quotient and remainder upon dividing x by y. For example, you would want divmod 17 5 to return (3,2). This is a built-in function in Python but not in SML, but is easily defined in SML using the built-in operators div and mod. The resulting function would have a type of the form 'a -> 'a -> 'a*'a -- but for a specific type (namely int). You would have to do something which is a bit less natural (such as what you did in your answer to your question) to come up with a polymorphic example.

Function Composition VS Function Application

Do anyone can give example of function composition?
This is the definition of function composition operator?
(.) :: (b -> c) -> (a -> b) -> a -> c
f . g = \x -> f (g x)
This shows that it takes two functions and return a function but i remember someone has expressed the logic in english like
boy is human -> ali is boy -> ali is human
What this logic related to function composition?
What is the meaning of strong binding of function application and composition and which one is more strong binding than the other?
Please help.
Thanks.
(Edit 1: I missed a couple components of your question the first time around; see the bottom of my answer.)
The way to think about this sort of statement is to look at the types. The form of argument that you have is called a syllogism; however, I think you are mis-remembering something. There are many different kinds of syllogisms, and yours, as far as I can tell, does not correspond to function composition. Let's consider a kind of syllogism that does:
If it is sunny out, I will get hot.
If I get hot, I will go swimming.
Therefore, if it is sunny about, I will go swimming.
This is called a hypothetical syllogism. In logic terms, we would write it as follows: let S stand for the proposition "it is sunny out", let H stand for the proposition "I will get hot", and let W stand for the proposition "I will go swimming". Writing α → β for "α implies β", and writing ∴ for "therefore", we can translate the above to:
S → H
H → W
∴ S → W
Of course, this works if we replace S, H, and W with any arbitrary α, β, and γ. Now, this should look familiar. If we change the implication arrow → to the function arrow ->, this becomes
a -> b
b -> c
∴ a -> c
And lo and behold, we have the three components of the type of the composition operator! To think about this as a logical syllogism, you might consider the following:
If I have a value of type a, I can produce a value of type b.
If I have a value of type b, I can produce a value of type c.
Therefore, if I have a value of type a, I can produce a value of type c.
This should make sense: in f . g, the existence of a function g :: a -> b tells you that premise 1 is true, and f :: b -> c tells you that premise 2 is true. Thus, you can conclude the final statement, for which the function f . g :: a -> c is a witness.
I'm not entirely sure what your syllogism translates to. It's almost an instance of modus ponens, but not quite. Modus ponens arguments take the following form:
If it is raining, then I will get wet.
It is raining.
Therefore, I will get wet.
Writing R for "it is raining", and W for "I will get wet", this gives us the logical form
R → W
R
∴ W
Replacing the implication arrow with the function arrow gives us the following:
a -> b
a
∴ b
And this is simply function application, as we can see from the type of ($) :: (a -> b) -> a -> b. If you want to think of this as a logical argument, it might be of the form
If I have a value of type a, I can produce a value of type b.
I have a value of type a.
Therefore, I can produce a value of type b.
Here, consider the expression f x. The function f :: a -> b is a witness of the truth of proposition 1; the value x :: a is a witness of the truth of proposition 2; and therefore the result can be of type b, proving the conclusion. It's exactly what we found from the proof.
Now, your original syllogism takes the following form:
All boys are human.
Ali is a boy.
Therefore, Ali is human.
Let's translate this to symbols. Bx will denote that x is a boy; Hx will denote that x is human; a will denote Ali; and ∀x. φ says that φ is true for all values of x. Then we have
∀x. Bx → Hx
Ba
∴ Ha
This is almost modus ponens, but it requires instantiating the forall. While logically valid, I'm not sure how to interpret it at the type-system level; if anybody wants to help out, I'm all ears. One guess would be a rank-2 type like (forall x. B x -> H x) -> B a -> H a, but I'm almost sure that that's wrong. Another guess would be a simpler type like (B x -> H x) -> B Int -> H Int, where Int stands for Ali, but again, I'm almost sure it's wrong. Again: if you know, please let me know too!
And one last note. Looking at things this way—following the connection between proofs and programs—eventually leads to the deep magic of the Curry-Howard isomorphism, but that's a more advanced topic. (It's really cool, though!)
Edit 1: You also asked for an example of function composition. Here's one example. Suppose I have a list of people's middle names. I need to construct a list of all the middle initials, but to do that, I first have to exclude every non-existent middle name. It is easy to exclude everyone whose middle name is null; we just include everyone whose middle name is not null with filter (\mn -> not $ null mn) middleNames. Similarly, we can easily get at someone's middle initial with head, and so we simply need map head filteredMiddleNames in order to get the list. In other words, we have the following code:
allMiddleInitials :: [Char]
allMiddleInitials = map head $ filter (\mn -> not $ null mn) middleNames
But this is irritatingly specific; we really want a middle-initial–generating function. So let's change this into one:
getMiddleInitials :: [String] -> [Char]
getMiddleInitials middleNames = map head $ filter (\mn -> not $ null mn) middleNames
Now, let's look at something interesting. The function map has type (a -> b) -> [a] -> [b], and since head has type [a] -> a, map head has type [[a]] -> [a]. Similarly, filter has type (a -> Bool) -> [a] -> [a], and so filter (\mn -> not $ null mn) has type [a] -> [a]. Thus, we can get rid of the parameter, and instead write
-- The type is also more general
getFirstElements :: [[a]] -> [a]
getFirstElements = map head . filter (not . null)
And you see that we have a bonus instance of composition: not has type Bool -> Bool, and null has type [a] -> Bool, so not . null has type [a] -> Bool: it first checks if the given list is empty, and then returns whether it isn't. This transformation, by the way, changed the function into point-free style; that is, the resulting function has no explicit variables.
You also asked about "strong binding". What I think you're referring to is the precedence of the . and $ operators (and possibly function application as well). In Haskell, just as in arithmetic, certain operators have higher precedence than others, and thus bind more tightly. For instance, in the expression 1 + 2 * 3, this is parsed as 1 + (2 * 3). This is because in Haskell, the following declarations are in force:
infixl 6 +
infixl 7 *
The higher the number (the precedence level), the sooner that that operator is called, and thus the more tightly the operator binds. Function application effectively has infinite precedence, so it binds the most tightly: the expression f x % g y will parse as (f x) % (g y) for any operator %. The . (composition) and $ (application) operators have the following fixity declarations:
infixr 9 .
infixr 0 $
Precedence levels range from zero to nine, so what this says is that the . operator binds more tightly than any other (except function application), and the $ binds less tightly. Thus, the expression f . g $ h will parse as (f . g) $ h; and in fact, for most operators, f . g % h will be (f . g) % h and f % g $ h will be f % (g $ h). (The only exceptions are the rare few other zero or nine precedence operators.)