Recursive list
Way, way back we looked at a function to estimate the value of the sin function utilizing its representation as a Taylor polynomial about x = 0. When one looks closely at that Taylor polynomial, one can observe a pattern in the coefficients involving the infinite sequence 0, 1, 0, -1, 0, 1, 0, -1, .... My buddy Marcelo in his formulation of that Taylor polynomial wrote this function that for a given n produces the first n values of this sequence as a list:
let rec sin_coeff n = match n with | 0 -> [] | 1 -> [0.] | 2 -> [0.; 1.] | 3 -> [0.; 1.; 0. ] | _ -> 0. :: 1. :: 0. :: -1. :: sin_coeff (n-4)He mused to me on the day that "surely there is a more elegant way to produce this list?". Oh, by golly Marcelo there certainly is!
let rec sin_coeff = 0 :: 1 :: 0 :: -1 :: sin_coeffThis little construction builds the list value
sin_coeff
recursively (that is, in terms of itself). Now, of course it's not impossible to define structures like this in C or C++ but good luck matching the brevity and elegance afforded to us in OCaml for this sort of thing! We still need a little function of course that can pull off this endless list a list containing just the first n elements. The ubiquitous take
function will do for this purpose and I show it here just for completeness.
let rec list_take k l = if k <= 0 then [] else match l with | [] -> [] | (x :: xs) -> x :: (list_take (k-1) xs)