Registered: Sep, 2005
Re: Typing like a Functional Programmer
Posted: Nov 28, 2006 10:34 AM
> This function has STATE.
It has an immutable state, which is not what imperative programmers understand when they talk about state
> It is an Object, not a Function.
Many languages see functions as object, and every FP language does. In fact, lambda calculus (on which many FP are at least loosely based) is based on the axiom that functions are objects, and are the base building blocks of everything.
> I thought the big advantage of FP was no states
One of the advantaces of FP is the absence of state mutations. In this case, there is no state mutation.
> Bye the way, if I go
> add_ints(6,7); (pardon me mashing the syntax)
> what gets returned? 18 or 13? And how do you know?
They're two completely unrelated calls.
add_ints(5) returns a function with an arity of 1 (it has a single argument) which perform the equivalent of "add_ints(5,x)" with x being the argument of the new function
add_ints(6,7) returns 13
Of course the C-like notation makes this extremely unwieldy, Haskell makes currying much cleaner and clearer:
is the type definition of a single value
(Int -> Int)
This arrow notation is the type definition of a function. This function takes an Int parameter (before the arrow) and returns an Int (after the arrow). Type definitions are read from left to right by the way.
Now if we expand this to the addition, we get this:
Int -> Int -> Int
Takes an Int, then takes an other Int, and returns an Int.
If we add parens, we can get either:
(Int -> Int -> Int)
Int -> (Int -> Int)
Which mean exactly the same thing: "function which takes a parameter of type Int, then takes a parameter of type Int, then returns a value of type Int", which is equivalent to "function which takes a parameter of type Int, then returns a function which takes a parameter of type Int, then returns a value of type Int.
And if we check the code itself, the basic application would be
add 5 3
which can also be written
(add 5 3)
(add 5) 3
In the end, what "add 5" does is return an anonymous function of type (Int -> Int), to which we pass the parameter "3", whether we perform the second parameter passing explicitely or implicitely
> So I assume this binding would be to the first parameter,
> so that:
> a = sub(7,2); // a is now 5
> f = sub(3);
> b = f(7); // b is now 4
> Have I got it?
That's not exactly it, b would be -4.