递归遍历F#中的数组 [英] Recursively iterating over an array in F#

查看:128
本文介绍了递归遍历F#中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个相当简单的要求,但我有F#的语法的麻烦。我需要创建一个函数来递归遍历数组二维,每一个条件满足时增加的计数器。在这种情况下,该功能将一个ID作为参数,然后检查该ID多少次是内阵列内present。我在想是这样的:

This is a rather simple request, but I am having trouble with F#'s syntax. I need to create a function to iterate over a bidimensional array recursively, increasing a counter every time a condition is met. In this case, the function takes an ID as a parameter, then checks to see how many times that ID is present inside the inner arrays. I was thinking of something like this:

let runner array count =  
    match count with  
    |0 -> (exit loop)  
    |n -> (perform function)  
        runner array count-1

有关递归迭代函数的一般结构。但是,有几个事情,我不知道。什么是F#中退出递归循环(即基本情况)的条件是什么?如何构建这种所以它穿过两个主及子阵列检查该ID?我如何让这个与递归循环的每次运行的计数器增加,假设我不能使用可变的功能呢?任何帮助将是AP preciated。

For the general structure of the recursive iteration function. However, there are several thing I'm not sure about. What are the conditions for exiting the recursive loop (ie, the base case) in F#? How do I structure this so it traverses both the main and sub-arrays to check for the ID? And how do I make it so that the counter increases with each run of the recursive loops, assuming I can't use mutable functions? Any help would be appreciated.

推荐答案

有一个更通用的方式来做到这一点。你想折叠一个二维数组。他们没有Array2D模块中定义的折叠,但你可以写一个。

There is a more generic way to do it. You want to fold over a 2d array. They don't have a fold defined in the Array2D module, but you can write one.

let fold f state (arr: 'a [,]) =
    Seq.cast<'a> arr
    |> Seq.fold f state

我们欺骗这里一点,投给我们从阵列中,我们在后面传递到规则的折叠元素的平面序列。所以现在你可以这样做:

We "cheat" a little here, cast gives us a flat sequence of elements from the array, which we later pass to a regular fold. So now you can do:

 array |> fold (fun counter e -> if cond e then counter+1 else counter) 0

其中cond是要检查的条件。

where cond is the condition you want to check.

这篇关于递归遍历F#中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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