在haskell中递归期间打印结果 [英] Printing a result during a recursion in haskell

查看:154
本文介绍了在haskell中递归期间打印结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  n  - >我开始学习Haskell,并且正在制作一个程序来执行迭代过程。 n / 2(甚至n)
n - > 3n + 1(对于奇数n)

所以我得到了这么多:`

 链n | n == 0 =错误你在说什么? 
| n == 1 =错误Finished
| rem n 2 == 0 = chain(n`div` 2)
| rem 2 / = 0 = chain(3 * n + 1)

`
这项工作?
但是它只是在幕后进行计算,有没有什么办法让它显示或导出每次迭代时n的结果,直到它达到1,以便我可以在以后找到列表的长度?



在附注中,有没有办法让GHCi开始在特定的文件夹中?(我正在使用windows)

解决方案

您可以让它像这样返回链中的结果列表:

  chain n | n == 0 =错误你在说什么? 
| n == 1 = []
| rem n 2 == 0 =(n`div` 2):chain(n`div` 2)
|否则=(3 * n + 1):链(3 * n + 1)

会得到如下结果:

  * Main>链3 
[10,5,16,8,4,2,1]
*主要>连锁店7
[22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]


I am beginning to learn Haskell and am making a program to do the iterative process:

n -> n/2 (for even n)
n -> 3n+1 (for odd n)

So I got this far:`

chain n     | n == 0       = error "What are you on about?"
            | n == 1       = error "Finished"
            | rem n 2 == 0 = chain (n `div` 2) 
            | rem n 2 /= 0 = chain (3 * n + 1)

` Will this work? But it only does the calculations behind the scenes, is there any way to make it display or export as list the result for n on each iteration until it reaches 1 so I can find the length of the list later?

On a side note, is there any way to make GHCi begin in a specific folder ?(I'm using windows)

解决方案

You could have it return a list of the results in the "chain" like this:

chain n     | n == 0       = error "What are you on about?"
            | n == 1       = []
            | rem n 2 == 0 = (n `div` 2) : chain (n `div` 2)
            | otherwise    = (3 * n + 1) : chain (3 * n + 1)

Now you'll get results like these:

*Main> chain 3
[10,5,16,8,4,2,1]
*Main> chain 7
[22,11,34,17,52,26,13,40,20,10,5,16,8,4,2,1]

这篇关于在haskell中递归期间打印结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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