I have the following two functions (I realise they are badly written, and couldn’t possibly work) but they come from an introduction to functional programming and illustrate the need for a base case in recursion.
sum1 l = head l + sum1 (tail l)
sum2 :: [Float] -> Float
sum2 l = head l + sum2 (tail l)
So the only difference apart from the names, is that one has a type signature and the other doesn’t. If I load them in to WinGCHi (although I’ve also tried it on repl.it), then evaluating sum2 [1…10] gives, as I’d expect, an exception, but evaluating sum1 [1…10] hangs until interrupted (see console log below).
Prelude> :load “ss.hs”
[1 of 1] Compiling Main ( ss.hs, interpreted )
Ok, modules loaded: Main.
*Main> :t sum1
sum1 :: Num a => [a] -> a
*Main> :t sum2
sum2 :: [Float] -> Float
*Main> sum1 [1…10]
Interrupted.
*Main> sum2 [1…10]
*** Exception: Prelude.head: empty list
*Main> _
The types of the two functions are basically the same.
I can’t understand why the difference in the evaluations.
John