When I define a recursive function in F# thus:
let rec recursiveSum inputs =
let startState = 0.0m
if List.length inputs = 1 then
startState + inputs.Head
else
let t = List.tail inputs
startState + inputs.Head + recursiveSum t
...all is good. When I attempt to avoid the "empty list" problem thus:
let rec recursiveSum inputs =
let startState = 0.0m
**if List.isEmpty inputs then startState**
if List.length inputs = 1 then
startState + inputs.Head
else
let t = List.tail inputs
startState + inputs.Head + recursiveSum t
...I get yelled at:
recursion.fsx(5,9): error FS0001: This expression was expected to have type
unit
but here has type
decimal
What am I missing here?
From the docs:
You're missing said
else.(N.b. I've used
elifhere rather than nesting anotherifexpression; hopefully that's not too much of a distraction.)That said, your logic involving
startStateis highly suspect; it's always zero, and really serves no purpose here. Your state should probably be a parameter rather than a local value so it can be used as an accumulator:Lastly, let's make it idiomatic:
which can be shortened to