I am testing F # for the first time with little theoretical knowledge of previous functional programming.
I have written a small function to calculate the simple moving average in a list. Here it is:
let's rec sma n data = let length = List.length data if the length is <n then the data another thing (data from sma n.[..length-2]@ [List.average data.[length - n .. ]]
I was not really satisfied with this result. It seems awkward, and I've expected a more elegant solution, but I could not find it. Then I had a crazy idea, and I did it the other way around. I have calculated SMA by starting in the list and moving forward:
let's rec sma n data = if List.length data <n then data otherwise the data in the list.[.. n-1] :: sma n data.Tail
That's what I like the most, that's what I've been waiting for. But why can not I do it iterating from the beginning?
According to the F # documentation (https://docs.microsoft.com/en-us/dotnet/fsharp/language-reference/lists), I can easily refer to the first item in the list (
Head) and the rest of the list (
Tail), and I can use the
:: operator to create a list by adding a new element at the beginning. However, I do not have a similar way of referring to the last element, or to the list without the last element, nor do I have an operator to create a list by adding a new element at the end.
Why does this asymmetry exist? I learned a bit about Haskell in college, and I think it was symmetrical from the perspective.