Chalupa
Chalupa

Reputation: 367

Is there a way to save the length of a list in a variable while doing recursion?

let's say I have a recursive function that takes two lists and returns an int like so

fn ys (x:xs) 
       | --some condition = original length of (x:xs) 
       | otherwise = fn ys xs

I need to return the original length of the my input list (before recursion has messed with it) if condition one is true. Is there a way to save the original length?

Upvotes: 3

Views: 148

Answers (1)

Ørjan Johansen
Ørjan Johansen

Reputation: 18189

You can do the recursion with a "worker" function (traditionally named go), which allows you to refer to the original parameters and also to define extra variables:

fn ys xs' = go xs'
  where
    l = length xs'
    go (x:xs) 
           | --some condition = l
           | otherwise = go xs

You probably want a case for go [] as well.

Upvotes: 8

Related Questions