Reputation: 15
I am a beginner and I want to define a function which shows how many elements are in one list. I already created this :
elementsl n [] = n
elementsl n (_:xs) = elementsl (n+1) xs
But I need to give two inputs: 0
and a list.
how can I give only the list as a single input and still have a counter in my function?
Upvotes: 0
Views: 465
Reputation: 11913
Very simple, define a new function, and define the 'helper' function in a where
block:
elements ls = helper 0 ls --`helper' is your previous function, defined below:
where helper n [] = n
helper n (_:xs) = helper (1+n) xs
This will prevent helper
from being used elsewhere, but allows you to write your function in this way.
However, you could avoid this tail-recursion entirely, and just write:
elements [] = 0
elements (_:xs) = 1 + elements xs
and therefore avoid the need for two arguments. This second style is generally considered more idiomatic haskell.
Upvotes: 3