• Post Reply Bookmark Topic Watch Topic
  • New Topic

Functional Programming  RSS feed

 
Hussein Baghdadi
clojure forum advocate
Bartender
Posts: 3479
Clojure Mac Objective C
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi.
Well, I know this isn't the best forum to ask about "Functional Programming" but I didn't find a better place...
Consider please this Erlang code:

I don't understand whats happening when I call:
fac(5)
I'm not sure but it seems to me it is "Recursion", right?
5 * fac(4)
4 * fac(3)
3 * fac(2)
etc..
 
Tony Docherty
Bartender
Posts: 3271
82
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I've never seen code like this before but it looks like recursion to me and it looks like the function will stop recursing when it is called with an argument of 1.
 
Kai Witte
Ranch Hand
Posts: 356
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hello,

the ! function (I don't know the English name, and it is not in my dictionary - "faculty" perhaps?) is defined for natural numbers including 0 as


That code expresses this definition and thus provides a function to compute the ! for all numbers for which it is defined.

For n = 5: n! = 5! = 5* (5-1)! = 5*4*(4-1)!=5*4*3*(3-1)!=5*4*3*2*(2-1)! = 5*4*3*2*1

Kai
 
Pat Farrell
Rancher
Posts: 4686
7
Linux Mac OS X VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
This is the classic example of a recursive funtion.
In english Mathematics, it is called "factorial"
The values get big quickly, 10! is over a million, and every value highter than 10 adds at least another digit to the answer, so 11! is eight digits long, 12! is nine, etc.

This (X!) is the same as the number of permutations of a collection of size X
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!