【发布时间】:2016-10-23 17:48:11
【问题描述】:
我正在尝试做一些非常简单的事情作为家庭作业的一部分。我需要做的就是编写一个函数,它接收代表三角形底边和高度长度的 2 元组数字列表,并返回与这些三角形对应的区域列表。其中一个要求是我通过定义一个函数并在where 子句中声明它的类型来做到这一点。到目前为止我尝试过的所有东西都无法编译,这就是我所得到的:
calcTriangleAreas xs = [triArea x | x<-xs]
where triArea:: (Num, Num) -> Num --this uses 4 preceding spaces
triArea (base, height) = base*height/2
这失败并出现错误The type signature for ‘triArea’ lacks an accompanying binding,对我来说这听起来像是 triArea 没有在 where 子句中定义。好的,让我们缩进它以匹配where:
calcTriangleAreas xs = [triArea x | x<-xs]
where triArea:: (Num, Num) -> Num --this uses 4 preceding spaces
triArea (base, height) = base*height/2 --... and so does this
这个无法编译特别无信息的错误消息parse error on input triArea。只是为了好玩,让我们尝试多缩进一点,因为不知道还能做什么:
calcTriangleAreas xs = [triArea x | x<-xs]
where triArea:: (Num, Num) -> Num --this uses 4 preceding spaces
triArea (base, height) = base*height/2 --this has 8
但是,没有骰子,失败并显示相同的parse error 消息。我尝试用等效的 4 空格制表符替换其中每一个中的间距,但这并没有
帮助。前两个使用制表符产生与使用空格相同的错误,但最后一个如下所示:
calcTriangleAreas xs = [triArea x | x<-xs]
where triArea:: (Num, Num) -> Num --this uses a preceding tab character
triArea (base, height) = base*height/2 --this has 2
给出错误信息
Illegal type signature: ‘(Num, Num) -> Num triArea (base, height)’
Perhaps you intended to use ScopedTypeVariables
In a pattern type-signature
我不知道那是什么意思,但它似乎突然忽略了换行符。我一直在阅读“Learn You a Haskell”,并且我应该能够使用前三章中提供的信息来做到这一点,但是我已经搜索了那些并且他们从未指定函数定义的类型在那些章节的where 子句中。作为记录,他们的例子似乎与间距无关,我复制了其中一个的风格:
calcTriangleAreas xs = [triArea x | x<-xs]
where triArea:: (Num, Num) -> Num --4 preceding spaces
triArea (base, height) = base*height/2 --10 preceding spaces
但这也编译失败,吐出完全无法理解的错误信息:
Expecting one more argument to ‘Num’
The first argument of a tuple should have kind ‘*’,
but ‘Num’ has kind ‘* -> GHC.Prim.Constraint’
In the type signature for ‘triArea’: triArea :: (Num, Num) -> Num
In an equation for ‘calcTriangleAreas’:
calcTriangleAreas xs
= [triArea x | x <- xs]
where
triArea :: (Num, Num) -> Num
triArea (base, height) = base * height / 2
当我 google/hoogle 时我找不到任何东西,我查看了 this question,但它不仅显示了 haskell
高级让我阅读,但根据内容我不相信他们和我有同样的问题。我尝试指定calcTriangleAreas 的类型,并尝试将triArea 规范中的类型别名为Floating,坦率地说,我已经走到了尽头。我的文件的第一行是module ChapterThree where,但除此之外,我在每个示例中显示的代码就是整个文件。
我正在使用 32 位 Linux Mint 18,我正在使用 ghc ChapterThree.hs Chapter3UnitTests.hs -o Test 进行编译,其中 ChapterThree.hs 是我的文件,单元测试由我的老师提供,因此我可以轻松判断我的程序是否有效(它从来没有进入ChapterThreeUnitTests.hs的编译步骤,所以我认为内容并不重要),我的ghc版本是7.10.3。
编辑:请注意,如果我完全删除类型规范,一切都编译得很好,并且该函数通过了所有相关的单元测试。
请救我脱离我的疯狂。
【问题讨论】: