使用列表递归 - Haskell [英] Recursion using lists - Haskell

查看:99
本文介绍了使用列表递归 - Haskell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图编写一个递归函数,它将包含一个整数列表的列表作为输入并返回一个类型为([Int],Int)的元组。
([Int],Int)



这是用于提供棋盘的棋盘游戏:

  [[5,4,3,8,6],
[0,2,1,0,7],
[ 0,1,9,4,3],
[2,3,4,0,9]]

这将是一个有4行5列的电路板。列表中的数字是硬币值。
这个棋盘游戏的目标是从列表顶部到底部收集硬币。您可以从顶行的任何位置开始向下移动,您可以直行,也可以沿着对角线向左或向右移动。你会想要的路径,将给你最大的总币值。



我已经创建了第一个函数,您可以输入路径列表[([Int], Int)],它返回最大币值的路径([Int],Int)。

现在我需要创建一个函数来实际生成路径列表我将输入到第一个函数中。



我知道我将不得不使用递归。
我会输入板子(如上图)和起始栏。
我将不得不采取列号,然后创建所有可能路径的列表。
如果我以列号开始,我下一个可能的步骤是位置(在下一行) - 相同的列号,列号-1和列号+1。我需要递归调用这个,直到达到底部。



我如何能够随时存储这些路径步骤,然后存储所有可能路径的最终列表?



([Int],Int) - [Int]是列表/列号或行中的位置,Int是硬币值。

我是新来的哈斯克尔,虽然我明白我要做什么,但编写代码真的很难。

不要在惯用功能代码中存储某些变量的中间值。相反,你把它们作为一个累积参数,你使用一个函数比如foldr来传递。

http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude。 html#v:foldr


I am trying to write a recursive function that will take a list containing a list of integers as an input and return a tuple of type ([Int],Int). ([Int],Int)

This is for a "board game" where you are supplied with a board:

 [[5,4,3,8,6],
  [0,2,1,0,7],
  [0,1,9,4,3],
  [2,3,4,0,9]]

This would be a board with 4 rows and 5 columns. The numbers inside the list are "coin values". The objective of this board game would be to go from the top of the list to the bottom collecting the coins. You are able to start in any position from the top row and to move down, you can go straight down, or diagonally to left or right. You would want the path that will give you the largest total coin values.

I've created a first function where you input a list of paths [([Int],Int)] and it returns the path ([Int],Int) with maximum coin value.

Now I need to create a function to actually generate the list of paths that I will input into the first function.

I know that I will have to use recursion. I will input the board (like one above) and a starting column. I will have to take the column number and then create a list of all possible paths. If I start with a column number, my next possible steps are positions (in the next row)- same column number, column num -1 and column num +1. I would need to recursively call this until I reach the bottom.

How would I be able to store these path steps as I go and then store the final - list of all possible paths?

([Int],Int) - [Int] is the position in list / column numbers or the rows and the Int is the coin value.

I'm new to haskell and while I understand what I have to do, it's really difficult to write the code.

解决方案

You don't "store" intermediate values in some variable in idiomatic functional code. Rather, you keep them as an accumulating parameter which you pass along using a function such as foldr.

http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:foldr

这篇关于使用列表递归 - Haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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