haskell

Intuitively, how does Haskell find the length of a list without using a standard length function?


I just started learning Haskell and was trying to write a program which computes the number of elements in a list. I found this code online:

listnumber :: [Int] -> Int 
listnumber [] = 0
listnumber (x:xs) =1 + listnumber xs

After loading in GHCi the program returns the length of the list as expected. But how does this code work intuitively?


Solution

  • 1| listnumber :: [Int] -> Int 
    2| listnumber [] = 0
    3| listnumber (x:xs) =1 + listnumber xs
    

    The first line pretty much says, that the function takes a list with Int's as argument and returns an Int.

    The second line is the edge case, means if you call the function with an empty list it will return 0.

    The 3rd line uses pattern matching to chop off the first element(x) of a list and the rest(xs). Now you just add 1 for the element x and call the function again(recursion) with the rest of the list, which will go on until it hits the edge case, an empty list.