尾递归的元素总和

问题描述 投票:0回答:1

我目前正在尝试学习F#中的尾递归,所以说我有一个函数,它接受一个列表,每个元素乘以3,然后得到列表的总和。哪些代码看起来像这样

let calc L = L |> List.map (fun x -> (x*3)) |>  List.sum

如何使用辅助函数使其成为Tail Recursive函数。

let _calc result L = 
  match L with 
  | [] -> result
  | hd::tl -> ???

let calc L = 
  match L with 
  | [] -> raise (System.ArgumentException("List cannot be empty"))
  | hd::tl _calc hd tl 
f# pattern-matching tail-recursion
1个回答
2
投票

我不想完全给出答案,所以:

sum的尾递归定义开始

let rec _calc result L = 
  match L with 
  | [] -> result
  | hd::tl -> _calc (result + hd) tl

let sum L = _calc 0 L

现在需要改变以将每个元素乘以3?

(另请注意,let calc L = L |> List.map (fun x -> (x*3)) |> List.sum将在空列表中返回0,不会引发异常。除非是必需的,否则不需要在尾递归版本中强制执行异常。)

© www.soinside.com 2019 - 2024. All rights reserved.