如何在没有forloop的情况下使用递归嵌套for循环在haskell中 [英] How to use recursion nested for loop in haskell without 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屋!