在haskell中的奇数/偶数函数中的相互递归 [英] Mutual recursion in odd/even functions in haskell

查看:597
本文介绍了在haskell中的奇数/偶数函数中的相互递归的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Graham Hutton的Haskell编程的第6章中,有一节叫做6.5相互递归,它包含以下示例:

  even :: Int  - > Bool 
even 0 = True
even(n + 1)= odd n

odd :: Int - > Bool
odd 0 = False
odd(n + 1)= even n

我想尝试一下。我把代码放在Hof.hs文件中,运行 ghci (版本7.8.3),输入

 :l Hof.hs 

并获得以下错误消息:

 
Hof.hs:3:7:模式中的分析错误:n + 1
失败,模块加载:无。

为什么我会收到此消息?是代码在语法上是过时的还是什么?

解决方案

  even :: Int  - > Bool 
even 0 = True
even n = odd(n-1)

odd :: Int - > Bool
odd 0 = False
odd n = even(n - 1)

请注意,这个函数在负输入中失败了,所以你可能想用 abs 来扩充它。


In chapter 6 of "Programming in Haskell" by Graham Hutton there is a section called "6.5 Mutual recursion", that contains the following example:

even :: Int -> Bool
even 0       = True
even (n + 1) = odd n

odd :: Int -> Bool
odd 0       = False
odd (n + 1) = even n

I wanted to try it out. I put the code in Hof.hs file, ran ghci(version 7.8.3), typed

:l Hof.hs

and got the following error message

Hof.hs:3:7: Parse error in pattern: n + 1
Failed, modules loaded: none.

Why am I getting this message? Is the code syntactically out of date or something?

解决方案

n + k patterns have been removed from Haskell and are no longer available. Write it like this instead:

even :: Int -> Bool
even 0 = True
even n = odd (n - 1)

odd :: Int -> Bool
odd 0 = False
odd n = even (n - 1)

Note that this function fails horribly for negative inputs, so you probably want to augment it with abs.

这篇关于在haskell中的奇数/偶数函数中的相互递归的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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