有没有办法在进行递归时保存变量中列表的长度?

时间:2015-04-01 03:05:46

标签: list haskell functional-programming

让我们说我有一个递归函数,它接受两个列表并返回一个像这样的int

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

如果条件1为真,我需要返回输入列表的原始长度(在递归之前已经搞乱了)。 有没有办法保存原来的长度?

1 个答案:

答案 0 :(得分:8)

您可以使用“worker”函数(传统上命名为go)进行递归,这允许您引用原始参数并定义额外变量:

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

您可能也需要go []的案例。