OCaml - 返回包含输入列表中偶数位置的所有元素的列表 [英] OCaml - return a list containing all the elements in even position in the input list

查看:236
本文介绍了OCaml - 返回包含输入列表中偶数位置的所有元素的列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是OCaml的新手,现在我正试图实现一个函数,它返回一个列表,其中包含输入列表中偶数位置的所有元素。对于[1; 2; 3; 5],
返回[2; 5],而[1 3]返回[3];并为[i;am;new;to;ocaml]返回[am;to]。希望有人能给我一些建议来解决这个问题。

解决方案

这个问题没有什么特别的OCaml。最有可能你的主要任务是学会递归地解决问题。

递归解决问题的方法是将其分解为两种情况:

a。输入非常小,答案显而易见。

b。答案并不是很小,但是你已经有了一个适用于(严格)较小输入的函数。为了解决这个问题,你需要决定如何确定输入大小是否小得可笑(一个非常短的列表),以及如何使用另一个适用于较小列表的函数来解决您的问题,并使用更大的列表。那么你自己的函数就是那个函数(当递归调用时)。


I am new to OCaml, and I am now trying to implement a function that returns a list containing all the elements in even position in the input list. For [1;2;3;5] returns [2;5] and for [1 3] returns [3]; and for ["i";"am";"new";"to";"ocaml"] returns ["am";"to"]. Hope someone can give me some suggestions to solve this problem.

解决方案

There's nothing particularly OCaml-like in this problem. Most likely your main task is to learn to solve problems recursively.

The way to solve a problem recursively is to break it into two cases:

a. The input is so small the answer is ridiculously obvious.

b. The answer isn't so small, but you already have a function that works for (strictly) smaller inputs.

To solve the problem, you need to decide how to determine whether the input size is ridiculously small (a very short list), and how to use another function that works for smaller lists to solve your problem with a larger list. Then your own function is that other function (when called recursively).

这篇关于OCaml - 返回包含输入列表中偶数位置的所有元素的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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