计算haskell中数组的长度 - 非穷举模式错误 [英] Calculating the length of an array in haskell - non exhaustive patterns error

查看:147
本文介绍了计算haskell中数组的长度 - 非穷举模式错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里和网上搜索了一般情况,我找不到任何似乎回答这个问题的东西。我只是刚刚开始在Haskell为一个模块在大学里玩耍而我正在定义一个函数来计算一个数组的长度(本质上是预先存在的长度函数)。



在我的讲义中,函数给出如下:

$ p $ let len [] = 0
让len(h:t)= 1 + len t

这对我有意义,它不会似乎没有遗漏任何东西,我也看到其他地方也发布了非常类似的东西,但是在GHCi中它抛出了非穷举模式的错误,我不能为了我的生活找出原因。



任何帮助将不胜感激,谢谢

解决方案

声明,其中第二个阴影第一个。



您需要声明 len 作为一个带有两个子句的函数。在GHCi中,您可以这样做:

 :{
let len [] = 0
len(h:t)= 1 + len t
:}

:{...:} 表单允许您在 *。hs 文件中输入多行声明。

  GHCi,7.6.3版:http://www.haskell.org/ghc/:?寻求帮助
加载包ghc-prim ...链接...完成。
加载包integer-gmp ...链接...完成。
加载程序包库...链接...完成。

前奏>让len [] = 0
Prelude>让len(h:t)= 1 + len t - 这会影响前面的len
Prelude> len [1,2,3]
***例外:< interactive>:3:5-25:函数len中的非穷举模式len
- 由于新len不处理一个空的列表

前奏> :{
Prelude |让len [] = 0
Prelude | len(h:t)= 1 + len t
Prelude | :}
前奏> len [1,2,3]
3
前奏>


I've searched around on here and on the net in general and I can't find anything that seems to be answering this question. I've only just starting playing around with Haskell for a module at university and I'm having an issue defining a function to calculate the length of an array (the pre-existing length function essentially).

In my lecture notes the function is given as:

let len [] = 0
let len (h:t) = 1 + len t

This makes sense to me, it doesn't seem to be missing anything and I've seen something very similar posted elsewhere as well, but in GHCi it's throwing a "Non-exhaustive patterns" error and I can't for the life of me figure out why.

Any help would be much appreciated, thanks

解决方案

What you have is two declarations, the second of which shadows the first.

You need to declare len as one function with two clauses. In GHCi, you can do that like this:

:{
let len [] = 0
    len (h:t) = 1 + len t
:}

the :{ ... :} form lets you enter multi-line declarations as you would in a *.hs file.

GHCi, version 7.6.3: http://www.haskell.org/ghc/  :? for help
Loading package ghc-prim ... linking ... done.
Loading package integer-gmp ... linking ... done.
Loading package base ... linking ... done.

Prelude> let len [] = 0
Prelude> let len (h:t) = 1 + len t -- this shadows the earlier len
Prelude> len [1, 2, 3]
*** Exception: <interactive>:3:5-25: Non-exhaustive patterns in function len 
    -- exception because the new len doesn't handle an empty list

Prelude> :{
Prelude| let len [] = 0
Prelude|     len (h:t) = 1 + len t
Prelude| :}
Prelude> len [1, 2, 3]
3
Prelude>

这篇关于计算haskell中数组的长度 - 非穷举模式错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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