合并两个清单 [英] Merge two lists

查看:85
本文介绍了合并两个清单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望以纯功能性的方式在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 = functionlet f x = match x with的简写,因此您不需要显式的args.另外,您的算法需要进行一些调整.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆