generated from jtr13/bookdown-template
-
Notifications
You must be signed in to change notification settings - Fork 31
/
Copy pathfprog.qmd
1643 lines (1255 loc) · 47.7 KB
/
fprog.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# Functional programming
Now that we are familiar with Git and Github, we can start with writing code. We
will learn how to write code using the functional programming paradigm.
Programming paradigms are ways to structure programs (or scripts).
This chapter will teach you the fundamentals of functional programming.
*Functional programming* might sound scary, but we will focus on only a handful
of concepts that are quite accessible but still provide many benefits. Using
these functional programming concepts will make your code more reliable, easier
to test, document, share, and ultimately rerun.
## Introduction
Remember that the philosophy of part one of this book is "don't repeat
yourself". In this chapter we will see how we can reduce the amount of code as
much as possible. In the previous chapter we’ve seen how Bruno was able to get
rid of many lines of code (that were all the same) by writing a single function:
```{r, eval = F}
make_plot <- function(country_level_data,
commune_level_data,
commune){
filtered_data <- commune_level_data %>%
filter(locality == commune)
data_to_plot <- bind_rows(
country_level_data,
filtered_data
)
ggplot(data_to_plot) +
geom_line(aes(y = pl_m2,
x = year,
group = locality,
colour = locality))
}
```
Now we are going to go one step further and not only learn how to write good
functions, but also how we can push the concept of "not repeating oneself" to
the extreme by using higher-order functions and function factories.
You are very likely already familiar with at least two elements of functional
programming: functions and lists. But functional programming is a complete
programming paradigm, so using functional programming is more than simply using
functions and lists (which you can use with other programming paradigms as
well).
Functional programming is a paradigm that relies exclusively on the evaluation
of functions to achieve the desired result. If you have already written your own
functions in the past, what follows will not be very new. But in order to write
a good functional program, the functions that you write and evaluate have to
have certain properties. Before discussing these properties, let's start with
*state*.
### The state of your program
Let's suppose that you start a fresh R session, and immediately run this line:
```{r, eval = F}
ls()
```
If you did not modify any of R's configuration files that get automatically
loaded on startup, you should see the following:
```{r, eval = F}
character(0)
```
Let's suppose that now you load some data:
```{r, eval = F}
data(mtcars)
```
and define a variable `a`:
```{r, eval = F}
a <- 1
```
Running `ls()` now shows the following:
```{r, eval = F}
[1] "a" "mtcars"
```
You have just altered the state of your program. You can think of the *state* as
a box that holds everything that gets defined by the user and is accessible at
any time. Let's now define a simple function that prints a sentence:
```{r, eval = F}
f <- function(name){
print(paste0(name, " likes lasagna"))
}
f("Bruno")
```
and here's the output:
```{r, eval = F}
[1] "Bruno likes lasagna"
```
Let's run `ls()` again:
```{r, eval = F}
[1] "a" "f" "mtcars"
```
Function `f()` is now listed there as well. This function has two nice properties:
- For a given input, it always returns exactly the same output. So `f("Bruno")` will always return "Bruno likes lasagna".
- When running this function, the state of the program does not get altered in any way.
### Predictable functions
Let's now define another function called `g()`, which does not have the same
properties as `f()`. First, let's define a function which does not always return
the same output given a particular input:
```{r, eval = F}
g <- function(name){
food <- sample(c("lasagna", "cassoulet", "feijoada"), 1)
print(paste0(name, " likes ", food))
}
```
For the same input, "Bruno", this function now produces (potentially) a
different output:
```{r, eval = F}
g("Bruno")
[1] "Bruno likes lasagna"
```
```{r, eval = F}
g("Bruno")
[1] "Bruno likes feijoada"
```
And now let's consider function `h()` that modifies the state of the program:
```{r, eval = F}
h <- function(name){
food <- sample(c("lasagna", "cassoulet", "feijoada"), 1)
if(exists("food_list")){
food_list <<- append(food_list, food)
} else {
food_list <<- append(list(), food)
}
print(paste0(name, " likes ", food))
}
```
This function uses the `<<-` operator. This operator saves definitions that are
made inside the body of functions (the body of a function are all the
instructions that go between the curly braces) in the global environment.
Before calling this function, run `ls()` again. You should see the same objects
as before, plus the new functions we've defined:
```{r, eval = F}
[1] "a" "f" "g" "h" "mtcars"
```
Let's now run `h()` once:
```{r, eval = F}
h("Bruno")
[1] "Bruno likes feijoada"
```
And now `ls()` again:
```{r, eval = F}
[1] "a" "f" "food_list" "g" "h" "mtcars"
```
Running `h()` did two things: it printed the message, but also created a
variable called "food_list" in the global environment with the following
contents:
```{r, eval = F}
food_list
```
```{r, eval = F}
[[1]]
[1] "feijoada"
```
Let's run `h()` again:
```{r, eval = F}
h("Bruno")
[1] "Bruno likes cassoulet"
```
and let's check the contents of "food_list":
```{r, eval = F}
food_list
```
```{r, eval = F}
[[1]]
[1] "feijoada"
[[2]]
[1] "cassoulet"
```
If you keep running `h()`, this list will continue growing. Let me say that I
hesitated to show you this; this is because if you didn't know `<<-`, you might
find the example above useful. But while useful, it is quite dangerous as well.
Generally, we want to avoid using functions that change the state as much as
possible because these functions are unpredictable, especially if randomness is
involved. It is much safer to define `h()` like this instead:
```{r, eval = F}
h <- function(name, food_list = list()){
food <- sample(c("lasagna", "cassoulet", "feijoada"), 1)
food_list <- append(food_list, food)
print(paste0(name, " likes ", food))
food_list
}
```
The difference now is that we made `food_list` the second argument of the
function. Also, we defined it as being optional by writing:
```{r, eval = F}
food_list = list()
```
This means that if we omit this argument, the empty list will get used by
default. This avoids the users from having to manually specify it.
We can call it like this:
```{r, eval = F}
food_list <- h("Bruno", food_list)
# since food_list is
# already defined, we don't
# need to start with an empty list
```
```{r, eval = F}
[1] "Bruno likes feijoada"
```
We save the output back to `food_list`. Let's now check its contents:
```{r, eval = F}
food_list
```
```{r, eval = F}
[[1]]
[1] "feijoada"
[[2]]
[1] "cassoulet"
[[3]]
[1] "feijoada"
```
The only thing that we now still need to deal with is the fact that the food
item gets chosen randomly. I'm going to show you the simple way of dealing with
this, but later in this chapter we are going to use the `{withr}` package for
situations like this. Let's redefine `h()` one last time:
```{r, eval = F}
h <- function(name, food_list = list(), seed = 123){
# We set the seed, making sure that we get
# the same selection of food for a given seed
set.seed(seed)
food <- sample(c("lasagna", "cassoulet", "feijoada"), 1)
# We now need to unset the seed, because
# if we don't, guess what, the seed will
# stay set for the whole session!
set.seed(NULL)
food_list <- append(food_list, food)
print(paste0(name, " likes ", food))
food_list
}
```
Let's now call `h()` several times with its default arguments:
```{r, eval = F}
h("Bruno")
```
```{r, eval = F}
[1] "Bruno likes feijoada"
[[1]]
[1] "feijoada"
```
```{r, eval = F}
h("Bruno")
```
```{r, eval = F}
[1] "Bruno likes feijoada"
[[1]]
[1] "feijoada"
```
```{r, eval = F}
h("Bruno")
```
```{r, eval = F}
[1] "Bruno likes feijoada"
[[1]]
[1] "feijoada"
```
As you can see, every time this function runs, it now outputs the same result.
Users can change the seed to have this function output, consistently, another
result.
### Referentially transparent and pure functions
A referentially transparent function is a function that does not use any
variable that is not also one of its inputs. For example, the following
function:
```{r, eval = F}
bad <- function(x){
x + y
}
```
is not referentially transparent, because `y` is not one of the function’s
inputs. What happens if you run `bad()` is that `bad()` needs to look for `y`.
Because `y` is not one of its inputs, `bad()` then looks for it in the global
environment. If `y` is defined there, it then gets used. Defining and using such
functions must be avoided at all costs because these functions are
unpredictable. For example:
```{r, eval = F}
y <- 10
bad <- function(x){
x + y
}
bad(5)
```
This will return `15`. But if `y <- 45` then `bad(5)` would this time around
return `50`. It is much safer, and clearer to make `y` an explicit input of the
function instead of having to keep track of `y`’s value (and it's so easy to do,
why just not do it):
```{r, eval = F}
good <- function(x, y){
x + y
}
```
`good()` is a referentially transparent function; it is much safer than `bad()`.
`good()` is also a pure function, because it's a function that does not interact
in any way with the global environment. It does not write anything to the global
environment, nor requires anything from the global environment. Function `h()`
from the previous section was not pure, because it created an object and wrote
it to the global environment (the `food_list` object). Turns out that pure
functions are thus necessarily referentially transparent.
So the first lesson in your functional programming journey that you have to
remember is to only use pure functions.
## Writing good functions
### Functions are first-class objects
In a functional programming language, functions are first-class objects.
Contrary to what the name implies, this means that functions, especially the
ones you define yourself, are nothing special. A function is an object like any
other, and can thus be manipulated as such. Think of anything that you can do
with any object in R, and you can do the same thing with a function. For
example, let's consider the `+()` function. It takes two numeric objects and
returns their sum:
```{r}
1 + 5.3
# or alternatively: `+`(1, 5.3)
```
You can replace the numbers with functions that return numbers:
```{r}
sqrt(1) + log(5.3)
```
It's also possible to define a function that explicitly takes another function
as an input:
```{r}
h <- function(number, f){
f(number)
}
```
You can call then use `h()` as a wrapper for `f()`:
```{r}
h(4, sqrt)
h(10, log10)
```
Because `h()` takes another function as an argument, `h()` is called a
higher-order function.
If you don't know how many arguments `f()`, the function you're wrapping, has,
you can use the `...`:
```{r}
h <- function(number, f, ...){
f(number, ...)
}
```
`...` are simply a place-holder for any potential additional argument that `f()`
might have:
```{r}
h(c(1, 2, NA, 3), mean, na.rm = TRUE)
h(c(1, 2, NA, 3), mean, na.rm = FALSE)
```
`na.rm` is an argument of `mean()`. As the developer of `h()`, I don't
necessarily know what `f()` might be, but even if I knew what `f()` would be and
knew all its arguments, I might not want to list them all. So I can use `...`
instead. The following is also possible:
```{r}
w <- function(...){
paste0("First argument: ", ..1,
", second argument: ", ..2,
", last argument: ", ..3)
}
w(1, 2, 3)
```
If you want to learn more about `...`, type `?dots` in an R console.
Because functions are nothing special, you can also write functions that return
functions. As an illustration, we'll be writing a function that converts
warnings to errors. This can be quite useful if you want your functions to fail
early, which often makes debugging easier. For example, try running this:
```{r}
sqrt(-5)
```
This only raises a warning and returns `NaN` (Not a Number). This can be quite
dangerous, especially when working non-interactively, which is what we will be
doing a lot later on. It is much better if a pipeline fails early due to an
error, than dragging a `NaN` value. This also happens with `log10()`:
```{r}
log10(-10)
```
So it could be useful to redefine these functions to raise an error instead, for
example like this:
```{r}
strict_sqrt <- function(x){
if(x < 0) stop("x is negative")
sqrt(x)
}
```
This function now throws an error for negative `x`:
```{r, eval = F}
strict_sqrt(-10)
```
```
Error in strict_sqrt(-10) : x is negative
```
However, it can be quite tedious to redefine every function that we need in our
pipeline, and remember, we don't want to repeat ourselves. So, because functions
are nothing special, we can define a function that takes a function as an
argument, converts any warning thrown by that function into an error, and
returns a new function. For example:
```{r}
strictly <- function(f){
function(...){
tryCatch({
f(...)
},
warning = function(warning)stop("Can't do that chief"))
}
}
```
This function makes use of `tryCatch()` which catches warnings raised by an
expression (in this example the expression is `f(...)`) and then raises an error
instead with the `stop()` function. It is now possible to define new functions
like this:
```{r}
s_sqrt <- strictly(sqrt)
```
```{r, eval = FALSE}
s_sqrt(-4)
```
```
Error in value[[3L]](cond) : Can't do that chief
```
```{r}
s_log <- strictly(log)
```
```{r, eval = FALSE}
s_log(-4)
```
```
Error in value[[3L]](cond) : Can't do that chief
```
Functions that return functions are called *function factories* and they're
incredibly useful. I use this so much that I've written a package, available on
CRAN, called `{chronicler}`, that does this:
```{r}
s_sqrt <- chronicler::record(sqrt)
```
```{r}
result <- s_sqrt(-4)
result
```
Because the expression above resulted in an error, `Nothing` is returned.
`Nothing` is a special value defined in the `{maybe}` package (check it out,
a very interesting package!). We can then even read a log to see what went
wrong:
```{r}
chronicler::read_log(result)
```
The `{purrr}` package also comes with function factories that you might find
useful (`{possibly}`, `{safely}` and `{quietly}`).
In part 2 we will also learn about assertive programming, another way of making
our functions safer, as an alternative to using function factories.
### Optional arguments
It is possible to make functions’ arguments optional, by using `NULL`. For
example:
```{r}
g <- function(x, y = NULL){
if(is.null(y)){
print("optional argument y is NULL")
x
} else {
if(y == 5) print("y is present"); x+y
}
}
```
Calling `g(10)` prints the message "Optional argument y is NULL", and
returns 10. Calling `g(10, 5)` however, prints "y is present" and returns 15. It
is also possible to use `missing()`:
```{r}
g <- function(x, y){
if(missing(y)){
print("optional argument y is missing")
x
} else {
if(y == 5) print("y is present"); x+y
}
}
```
I however prefer the first approach, because it is clearer which arguments are
optional, which is not the case with the second approach, where you need to read
the body of the function.
### Safe functions
It is important that your functions are safe and predictable. You should avoid
writing functions that behave like the `nchar()` base function. Let's see why
this function is not safe:
```{r}
nchar("10000000")
```
It returns the expected result of 8. But what if I remove the quotes?
```{r}
nchar(10000000)
```
What is going on here? I'll give you a hint: simply type `10000000` in the
console:
```{r}
10000000
```
`10000000` gets represented as `1e+07` by R. This number in scientific notation
gets then converted into the character "1e+07" by `nchar()`, and this conversion
happens silently. `nchar()` then counts the number of characters, and
*correctly* returns 5. The problem is that it doesn't make sense to provide a
number to a function that expects a character. This function should have
returned an error message, or at the very least raised a warning that the number
got converted into a character. Here is how you could rewrite `nchar()` to make
it safer:
```{r}
nchar2 <- function(x, result = 0){
if(!isTRUE(is.character(x))){
stop(paste0("x should be of type 'character', but is of type '",
typeof(x), "' instead."))
} else if(x == ""){
result
} else {
result <- result + 1
split_x <- strsplit(x, split = "")[[1]]
nchar2(paste0(split_x[-1],
collapse = ""), result)
}
}
```
This function now returns an error message if the input is not a character:
```{r, eval = F}
nchar2(10000000)
```
```
Error in nchar2(10000000) : x should be of type 'character', but is of type 'integer' instead.
```
This section is in a sense an introduction to assertive programming. As
mentioned in the section on function factories, we will be learning about
assertive programming in greater detail in part 2 of the book.
### Recursive functions
You may have noticed in the last lines of `nchar2()` (defined above) that
`nchar2()` calls itself. A function that calls itself in its own body is called
a recursive function. It is sometimes easier to define a function in its
recursive form than in an iterative form. The most common example is the
factorial function. However, there is an issue with recursive functions (in the
R programming language, other programming languages may not have the same
problem, like Haskell): while it is sometimes easier to write a function using a
recursive algorithm than an iterative algorithm, like for the factorial
function, recursive functions in R are quite slow. Let's take a look at two
definitions of the factorial function, one recursive, the other iterative:
```{r}
fact_iter <- function(n){
result = 1
for(i in 1:n){
result = result * i
}
result
}
fact_recur <- function(n){
if(n == 0 || n == 1){
result = 1
} else {
n * fact_recur(n-1)
}
}
```
Using the `{microbenchmark}` package we can benchmark the code:
```{r, eval = FALSE}
microbenchmark::microbenchmark(
fact_recur(50),
fact_iter(50)
)
```
```
Unit: microseconds
expr min lq mean median uq max neval
fact_recur(50) 21.501 21.701 23.82701 21.901 22.0515 68.902 100
fact_iter(50) 2.000 2.101 2.74599 2.201 2.3510 21.000 100
```
We see that the recursive factorial function is 10 times slower than the
iterative version. In this particular example it doesn't make much of a
difference, because the functions only take microseconds to run. But if you're
working with more complex functions, this is a problem. If you want to keep
using the recursive function and not switch to an iterative algorithm, there are
ways to make them faster. The first is called *trampolining*. I won't go into
details, but if you're interested, there is an R package that allows you to use
trampolining with R, aptly called
[`{trampoline}`](https://rdinnager.github.io/trampoline/)^[https://rdinnager.github.io/trampoline/].
Another solution is using the [`{memoise}`](https://memoise.r-lib.org/)^[https://memoise.r-lib.org/] package.
Again, I won't go into details. So if you want to use and optimize recursive
functions, take a look at these packages.
### Anonymous functions
It is possible to define a function and not give it a name. For example:
```{r, eval = F}
function(x)(x+1)(10)
```
Since R version 4.1, there is even a shorthand notation for anonymous functions:
```{r, eval = F}
(\(x)(x+1))(10)
```
Because we don't name them, we cannot reuse them. So why is this useful?
Anonymous functions are useful when you need to apply a function somewhere
inside a pipe once, and don't want to define a function just for this. This will
become clearer once we learn about lists, but before that, let's philosophize a
bit.
### The Unix philosophy applied to R
>This is the Unix philosophy: Write programs that do one thing and do it well. Write programs to work together. Write programs to handle text streams, because that is a universal interface.
*Doug McIlroy, in A Quarter Century of Unix*[^1]
[^1]: http://www.catb.org/~esr/writings/taoup/html/ch01s06.html
We can take inspiration from the Unix philosophy and rewrite it for our
purposes:
*Write functions that do one thing and do it well. Write functions that work together. Write functions that handle lists, because that is a universal interface.*
Strive for writing simple functions that only perform one task. Don’t hesitate
to split a big function into smaller ones. Small functions that only perform one
task are easier to maintain, test, document and debug. These smaller functions
can then be chained using the `|>` operator. In other words, it is preferable to
have something like:
```
a |> f() |> g() |> h()
```
where `a` is for example a path to a data set, and where `f()`, `g()` and `h()`
successively read, clean, and plot the data, than having something like:
```
big_function(a)
```
that does all the steps above in one go.
This idea of splitting the problem into smaller chunks, each chunk in turn split
into even smaller units that can be handled by functions and then the results of
these function combined into a final output is called composition.
The advantage of splitting `big_function()` into `f()`, `g()` and `h()` is that
you can *eat the elephant one bite at a time*, and also reuse these smaller
functions in other projects more easily. So what’s important is that you can
make small functions work together by sharing a common interface. The list is
usually a good candidate for this.
## Lists: a powerful data-structure
Lists are the second important ingredient of functional programming. In the R
philosophy inspired by the UNIX philosophy, I stated that *lists are a universal
interface* in R, so our functions should handle lists. This of course depends on
what it is you’re doing. If you need functions to handle numbers, then there's
little value in placing these numbers inside lists. But in practice, you will
very likely manipulate objects that are more complex than numbers, and this is
where lists come into play.
### Lists all the way down
Lists are extremely flexible, and most of the very complex objects classes that
you manipulate are actually lists, but just fancier. For example, a data frame
is a list:
```{r}
data(mtcars)
typeof(mtcars)
```
A fitted model is a list:
```{r}
my_model <- lm(hp ~ mpg, data = mtcars)
typeof(my_model)
```
A `ggplot` is a list:
```{r}
library(ggplot2)
my_plot <- ggplot(data = mtcars) +
geom_line(aes(y = hp, x = mpg))
typeof(my_plot)
```
It's lists all the way down, and it's not a coincidence; it’s because lists are
very powerful. So it's important to know what you can do with lists.
### Lists can hold many things
If you write a function that needs to return many objects, the only solution is
to place them inside a list. For example, consider this function:
```{r}
sqrt_newton <- function(a,
init = 1,
eps = 0.01,
steps = 1){
stopifnot(a >= 0)
while(abs(init**2 - a) > eps){
init <- 1/2 *(init + a/init)
steps <- steps + 1
}
list(
"result" = init,
"steps" = steps
)
}
```
This function returns the square root of a number using Newton's algorithm, as
well as the number of steps, or iterations, it took to reach the solution:
```{r}
result_list <- sqrt_newton(1600)
result_list
```
It is quite common to print the number of steps to the console instead of
returning them. But the issue with a function that prints something to the
console instead of returning it, is that such a function is not pure, as it
changes something outside of its scope (it prints to the console!). And if you
need the information that got printed (for example, if you want to count all the
steps it took to run the script from start to finish), it is lost. It gets
printed, and that’s it. It is preferable to instead make the function pure by
returning everything inside a neat list. It is then possible to separately save
these objects if needed:
```{r}
result <- result_list$result
result_steps <- result_list$steps
```
Or you could define functions that know how to deal with the list:
```{r}
f <- function(result_list){
list(
"result" = result_list$result * 10,
"steps" = result_list$steps + 1
)
}
f(result_list)
```
It all depends on what you want to do. But it is usually better to keep
everything neatly inside a list.
Lists can also hold objects of different types:
```{r}
list(
"a" = head(mtcars),
"b" = ~lm(y ~ x)
)
```
The list above has two elements, the first is the head of the `mtcars` data
frame, the second is a formula object. Lists can even hold other lists:
```{r}
list(
"a" = head(mtcars),
"b" = list(
"c" = sqrt,
"d" = my_plot # Remember this ggplot object from before?
)
)
```
Use this to your advantage.
### Lists as the cure to loops
Loops are incredibly useful, and you are likely familiar with them. The problem
with loops is that they are a concept from iterative programming, not functional
programming, and this is a problem because loops rely on changing the state of
your program to run. For example, let's suppose that you wish to use a for-loop
to compute the sum of the first 100 integers:
```{r}
result <- 0
for (i in 1:100){
result <- result + i
}
print(result)
```
If you run `ls()` now, you should see that there's a variable `i` in your global
environment. This could cause issues further down in your pipeline if you need
to re-use `i`. Also, writing loops is, in my opinion, quite error prone. But how
can we avoid using loops? Looping in a functional programming language involves
using higher-order functions and lists. A reminder: a higher-order function is a
function that takes another function as an argument. Looping is a task like any
other, so I can write a function that does the looping. This function, which
I’ll call `looping()`, will take a function as an argument, as well as a
list. The list will serve as the container to hold our numbers:
```{r}
looping <- function(a_list, a_func, init = NULL, ...){
# If the user does not provide an `init` value,
# set the head of the list as the initial value
if(is.null(init)){
init <- a_list[[1]]
a_list <- tail(a_list, -1)
}
# Separate the head from the tail of the list
# and apply the function to the initial value and the head of the list
head_list = a_list[[1]]
tail_list = tail(a_list, -1)
init = a_func(init, head_list, ...)
# Check if we're done: if there is still some tail,
# rerun the whole thing until there's no tail left
if(length(tail_list) != 0){
looping(tail_list, a_func, init, ...)
}
else {
init
}
}
```