如何在没有forloop的情况下使用递归嵌套for循环在haskell中 [英] How to use recursion nested for loop in haskell without forloop

查看:94
本文介绍了如何在没有forloop的情况下使用递归嵌套for循环在haskell中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设有一些嵌套for循环的动态数字来输出所有组合在这个例子中,有3个嵌套的forloop,来生成所有组合的列表,例如
[1,2,3],[1,3,5]等。

如果有N个嵌套forloop,如何使用递归做haskell?



伪代码

 对于我从1到5做
for j from 1 to 10 do
if i< j然后
for k从1到50 do
if j < k then
list1 :: [i,j,k]

未完成的forloop有编译错误

  forloop :: Integer  - >整数 - > [a] 
forloop n m
| n == 1 = 1
|否则=如果n> m
然后[(forloop n-1 m)] ++ [n]
else []

期望一个递归版本的函数,它可以保存在redis中,比如Action类型的.net框架

解决方案

假设每个嵌套层次都有一个范围结束的列表。考虑你如何生成列表,如果你有一个范围较小的列表的解决方案。

  solve :: [ Int]  - > Int  - > [[Int]] 
solve [] _ = [[]]
solve(r:t)i = [j:s | j< - [i + 1..r],s< - 解决t j]


assume there are dynamic number of nested for loop to output all combinations

in this example, there are 3 nested forloop, to generate a list of all combination such as [1,2,3], [1,3,5] etc.

if there are N nested forloop, how to use recursion to do in haskell?

pseudo code

for i from 1 to 5 do
     for j from 1 to 10 do
          if i < j then
          for k from 1 to 50 do
               if j < k then
                  list1 :: [i,j,k]

unfinished forloop has compile error

forloop :: Integer -> Integer -> [a]
forloop n m
    | n == 1 = 1
    | otherwise =  if n > m 
                     then [(forloop n-1 m)] ++ [n]
                     else []

expect a recursive version of function which can be saved in redis like Action type of .net framework

解决方案

Suppose you have a list of range end for each level of nesting. Consider how you are going to generate the lists, if you have a solution for the shorter list of ranges.

solve :: [Int] -> Int -> [[Int]]
solve [] _ = [[]]
solve (r:t) i = [j:s | j <- [i+1..r], s <- solve t j]

这篇关于如何在没有forloop的情况下使用递归嵌套for循环在haskell中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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