Recursion 替换列表F中的递归元素#
我现在正试图学习F#的基础知识,想知道如何递归地替换列表中的元素。因此,您可以这样做。对我链接的答案进行修改,以直接回答问题:Recursion 替换列表F中的递归元素#,recursion,f#,Recursion,F#,我现在正试图学习F#的基础知识,想知道如何递归地替换列表中的元素。因此,您可以这样做。对我链接的答案进行修改,以直接回答问题: let rec insert v i l = //v - value to substitute, i - index at which to substitute, l - the list match i, l with | 0, x::xs -> v::xs //this line does the actual replace |
let rec insert v i l = //v - value to substitute, i - index at which to substitute, l - the list
match i, l with
| 0, x::xs -> v::xs //this line does the actual replace
| i, x::xs -> x::insert v (i - 1) xs //simply iterates one further through the list
| i, [] -> failwith "index out of range" // the given index is outside the bounds of the list
请注意,这不是尾部递归,对于大型列表,这将导致堆栈溢出。如果需要执行这种类型的操作,数组或列表可能是更好的选择。对我链接的答案进行修改,以直接回答问题:
let rec insert v i l = //v - value to substitute, i - index at which to substitute, l - the list
match i, l with
| 0, x::xs -> v::xs //this line does the actual replace
| i, x::xs -> x::insert v (i - 1) xs //simply iterates one further through the list
| i, [] -> failwith "index out of range" // the given index is outside the bounds of the list
let replace index sub = List.mapi (fun i x -> if i = index then sub else x)
replace 0 'd' ['a';'b';'c']
> val it : char list = ['d'; 'b'; 'c']
请注意,这不是尾部递归,对于大型列表,这将导致堆栈溢出。如果需要执行这种类型的操作,数组或列表可能是更好的选择
let replace index sub = List.mapi (fun i x -> if i = index then sub else x)
replace 0 'd' ['a';'b';'c']
> val it : char list = ['d'; 'b'; 'c']
这符合您的标准,有两个小改动使其更符合F#风格:
不是一个完全相同的副本,但足够接近不重要。因此插入和替换是解决此问题的最佳方法?@Valener您应该能够基于Juliet在链接回答中提供的
insert
和remove
代码编写自己的replace
函数。只需稍加修改。好的,我会继续尝试。不是一个完全相同的副本,但足够接近无所谓。因此插入和替换是解决此问题的最佳方法?@Valener您应该能够基于Juliet在链接答案中提供的插入
和删除
代码编写自己的替换
函数。只需修改一下。好的,我会继续尝试。非常感谢!这很好用,非常感谢!太棒了,非常感谢!太棒了,非常感谢!