合并两个列表 [英] Merge two lists
本文介绍了合并两个列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望以纯函数方式在 F# 中合并 2 个列表.我很难理解语法.
I am looking to merge 2 lists in F# in a purely functional way. I am having a hard time understanding the syntax.
假设我有一个元组 ([5;3;8],[2;9;4])
当我调用函数时,它应该返回[5;2;3;9;8;4]
When I call the function, it should return [5;2;3;9;8;4]
这就是我到目前为止的原因,我敢肯定这是错误的.如果有人能以简单的方式解释它,我将不胜感激.
Here is why I have so far, which is wrong I am sure. If someone could explain it in a simple way I would be grateful.
let rec interleave (xs,ys) = function
|([], ys) -> ys
|(x::xs, y::ys) -> x :: y:: interleave (xs,ys)
推荐答案
你的功能几乎是正确的.let f = function
是 let f x = match x with
的简写,因此您不需要显式参数.此外,您的算法需要进行一些调整.
Your function is almost right. let f = function
is shorthand for let f x = match x with
so you don't need explicit args. Also, your algorithm needs some tweaking.
let rec interleave = function //same as: let rec interleave (xs, ys) = match xs, ys with
|([], ys) -> ys
|(xs, []) -> xs
|(x::xs, y::ys) -> x :: y :: interleave (xs,ys)
interleave ([5;3;8],[2;9;4]) //output: [5; 2; 3; 9; 8; 4]
这篇关于合并两个列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文