myfact.md (2431B)
1 # myfact: a C implementation of a factorial function 2 This file describes a C implementation of a factorial function. 3 It generates three files: 4 5 * `myfact.c`: the implementation of factorial 6 * `myfact.h`: the header file for factorial 7 * `main.c`: the main file, which includes and runs the factorial function 8 9 This is clearly over-engineered; it aims to only be an example of the power of literate programming. 10 11 If you want to generate the code, make sure you have the `vim-literate-markdown` plugin loaded in Vim. 12 Then, open this document in Vim, and run the command `:Tangle`. 13 The three files described above will be in the same directory as this file. 14 15 ## The main file 16 The main file is pretty simple: 17 18 <!-- :Tangle <^> main.c --> 19 ```c 20 <<main imports>> 21 int main() { 22 <<call the function from the header file>> 23 return 0; 24 } 25 ``` 26 27 As you can see, it just calls whatever we define in the header. 28 29 Now for the header -- let's do a factorial calculation. 30 31 ## Factorial calculation 32 The factorial function is recursive. 33 We'll make use of the following mathematical definitions: 34 35 ``` 36 0! = 1 37 n! = n × (n-1)! 38 ``` 39 40 Let's have a basic definition of the function like this: 41 42 <!-- :Tangle <> <factorial function> myfact.c --> 43 ```c 44 int myfact(int n) { 45 <<base case>> 46 <<recursive case>> 47 } 48 ``` 49 50 The base case is when n == 0: the result is 1. 51 Putting that into code: 52 53 <!-- :Tangle <base case> myfact.c --> 54 ```c 55 if (n == 0) return 1; 56 ``` 57 58 Going from the mathematical definition, the recursive case calls the factorial function. 59 Like this: 60 61 <!-- :Tangle <recursive case> myfact.c --> 62 ```c 63 return n*myfact(n-1); 64 ``` 65 66 The implementation file as a whole has this structure: 67 68 <!-- :Tangle <^> myfact.c --> 69 ```c 70 // No imports necessary 71 <<factorial function>> 72 ``` 73 74 And its corresponding header file just has the prototype: 75 76 <!-- :Tangle myfact.h --> 77 ```c 78 int myfact(int); 79 ``` 80 81 ## Calling it from the main file 82 Back to the main file now. 83 We've written our factorial function in `myfact.h`. 84 So, first, we need to `#include` our header file: 85 86 <!-- :Tangle <main imports> main.c --> 87 ```c 88 #include "myfact.h" 89 ``` 90 91 Then we need to call the factorial in the body of the main function: 92 93 <!-- :Tangle <call the function from the header file> main.c --> 94 ```c 95 printf("The factorial of %d is %d\n", 5, myfact(5)); 96 ``` 97 98 Of course, to be able to print, we need to include the IO header: 99 100 <!-- :Tangle <main imports>+ main.c --> 101 ```c 102 #include <stdio.h> 103 ```