Haskell count elements in a list tail recursion -


i have amount of card in list of cards through tail recursion. given following code:

amountcard :: int -> card -> [card] -> int 

my attempt far:

amountcard n c [] = n amountcard n k (x:xs) = if k == x amountcard (n+1) k xs else amountcard n k xs 

did use tail recursion here?

well wikipedia article says:

[a] tail call subroutine call performed final action of procedure. if tail call might lead same subroutine being called again later in call chain, subroutine said tail-recursive, special case of recursion. tail recursion (or tail-end recursion) particularly useful, , easy handle in implementations.

(formatting added)

now if use if-then-else , nothing after that, know body of then , else clause last things "procedure" do. since in body of these then , else clauses simple calls (there no "post processing" 1 + (amountcard n k xs)), yes indeed tail-recursion.

i more elegant use guards if-then-else structure:

amountcard n c [] = n amountcard n k (x:xs) | k == x = amountcard (n+1) k xs                       | otherwise = amountcard n k xs

furthermore in haskell wildcard pattern used if variable of no importance, like:

amountcard n _ [] = n amountcard n k (x:xs) | k == x = amountcard (n+1) k xs                       | otherwise = amountcard n k xs

furthermore noted @chepner, can convert code to:

amountcard n c [] = n amountcard n k (x:xs) = amountcard (if k == x n + 1 else n) k xs

and tail recursive, since body of second clause contains 1 call same function (with different arguments).


Comments

Popular posts from this blog

javascript - Clear button on addentry page doesn't work -

c# - Selenium Authentication Popup preventing driver close or quit -

tensorflow when input_data MNIST_data , zlib.error: Error -3 while decompressing: invalid block type -