Given the following function definition and assuming similar definitions for all positive integers give the type definition and code for a function called plus that will take as arguments two such functions representing integers and return a function that represents the sum of the two input integers. E.g. (plus one two)
should evaluate to a function that takes two arguments f x
and returns (f(f(f x)))
.
one f x = f x
two f x = f (f x)
three f x = f (f (f x)))
etc.
I am new to functional programming and I can't get my head around this. I firstly don't know how I can define the functions for all the positive integers without writing them out (which is obviously impossible). As in, if I have plus(sixty, forty)
, how can my function recognize that sixty is f applied 60 times to x
?
I am meant to be writing this in Miranda, but I am more familiar with Haskell, so help for either is welcome.
Apply equational reasoning1, and abstraction. You have
Thus, a successor function
next
is naturally defined, so thatthree = next two
. Yes, it is as simple as writingnext two
instead ofthree
in the equation above:This captures the pattern of succession.
f
will be used as a successor function, andx
as zero value. The rest follows. For instance,i.e.
one f x
will be used as a zero value bytwo
(instead of the "usual"x
), thus representingthree
. A "number"n
represents a succession of n+1
operations.The above, again, actually defines the general
plus
operation becausetwo
andone
are just two formal function parameters:The key thing to gasp here is that a function is an object that will produce a value, when called. In itself it's an opaque object. The "observer" arguments that we apply to it, supply the "meaning" for what it means to be zero, or to find a successor, and thus define what result is produced when we make an observation of a number's value.
1i.e. replace freely in any expression the LHS with the RHS of a definition, or the RHS with the LHS, as you see fit (up to the variables renaming of course, to not capture/shadow the existing free variables).