Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/haskell/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Haskell递归添加函数不工作_Haskell_Recursion - Fatal编程技术网

Haskell递归添加函数不工作

Haskell递归添加函数不工作,haskell,recursion,Haskell,Recursion,我试图编写一个Haskell函数,以递归方式确定列表是否处于任意值之下。由于某些原因,代码没有编译。我的错误如下 --declare function checkIfExpensive :: [Float] -> Float -> String --base case checkIfExpensive [] x = "You have enough money" checkIfExpensive list x = if x > 20 --recursive case

我试图编写一个Haskell函数,以递归方式确定列表是否处于任意值之下。由于某些原因,代码没有编译。我的错误如下

--declare function
checkIfExpensive :: [Float] -> Float -> String

--base case
checkIfExpensive [] x = "You have enough money"
checkIfExpensive list x = if x > 20
--recursive case
                                then "You don't have enough money"
                                else checkIfExpensive (init list) (last list + x)
编辑:通过将“tail”切换到“last”来编译代码。但是,现在我似乎每次运行代码时都会遇到不同的错误

下面是一些错误的样子

*Main> checkIfExpensive [5,5,5] 0

<interactive>:1:1: error: Data constructor not in scope: Ixve5
*Main> checkIfExpensive [1,1,1] 0

<interactive>:1:1: error: Variable not in scope: cpe
Prelude>
*Main>checkifpriced[5,5,5]0
:1:1:错误:数据构造函数不在范围内:Ixve5
*Main>CheckIfExplicate[1,1,1]0
:1:1:错误:变量不在范围内:cpe
序曲>

列表的尾部表示列表中第一个元素之后的所有内容。 例如,[1,2,3,4]的尾部就是[2,3,4]。您收到的错误明智地通知您不能将浮点添加到浮点列表中

通过考虑列表数据类型的归纳定义,明确了尾部函数的实现,即列表为空或由元素和列表构成

您可能在前面发现此问题的一种方法是观察尾部的类型,如下所示:

tail :: [a] -> [a]
获取列表的最后一个元素的正确方法是使用具有以下类型签名的最后一个函数:

last :: [a] -> a
我还建议使用
all::(a->Bool)->[a]->Bool
函数检查一个条件是否适用于整个列表。例如,给定一个浮动列表
xs
,您可以使用:

all (<= 20) xs

第一:
String
对于返回值来说太“大”了。只有两个(无穷多个)可能的返回值。改用
Bool
。(您始终可以编写单独的函数来选择要显示的消息。)

其次,已经有一个预定义的函数来确定列表中的任何元素是否满足您的条件:
any
函数

any :: Foldable t => (a -> Bool) -> t a -> Bool
列表是可折叠的,所以您只需编写

checkIfExpensive list = any (\x -> x > 20) list
如果仍要返回
字符串
,则
If
表达式可以测试
any
的返回值

checkIfExpensive :: [Float] -> String
checkIfExpensive list = if any (\x -> x > 20) list 
                        then "You don't have enough money"
                        else "You don't have enough money"

我意识到我误解了tail函数,并将其替换为最后一个函数。我的代码现在可以编译了,但在运行函数时,它给我带来了奇怪的错误。你确定键入的是你想要的吗?正如您所说,考虑到您的预期输入,这些错误毫无意义——但它所抱怨的变量名是由预期输入中的字符按顺序组成的。所以你的键盘好像坏了,缺了一些无法显示的字符?(但是我不知道您是如何键入您的帖子的,包括示例GHCi会话…)您不可能从这个命令中获得这些错误。如果程序中有不在作用域内的内容,则在加载程序时会显示,而不是在键入命令时。
checkIfExpensive list = any (\x -> x > 20) list
checkIfExpensive :: [Float] -> String
checkIfExpensive list = if any (\x -> x > 20) list 
                        then "You don't have enough money"
                        else "You don't have enough money"