2016-07-26 73 views
0

我对编程和Haskell很陌生,所以如果这是基本的应用程序。运行Haskell代码时出错

我在运行下面的程序时遇到了问题,但我不确定它是程序错误还是我不知道如何使用ghci

我写了一个程序,其行为类似于last,但是却将列表中倒数第二项返回到列表中。

我的代码是

main :: IO() 
main = return()  
lastButOne::[a]->a 
lastButOne xs = if length xs == 2 
       then head xs 
       else lastButOne (tail xs) 

程序编译就好了,但我似乎无法找到一种方法来没有给我一个错误运行。

教科书给出了运行一个程序,通过做模拟drop的例子在ghci

ghci> :load myDrop.hs 
Ok, modules loaded: Main. 
ghci> myDrop 3 "asdfg" 
"fg" 

以下然而,当我打开我的lastButOne.hs并试图给程序输入我得到以下

Prelude> :load lastButOne.hs 
[1 of 1] Compiling Main    (lastButOne.hs, interpreted) 
Ok, modules loaded: Main. 
*Main> lastButOne [a,b,c,d,e,f] 

<interactive>:2:13: error: Variable not in scope: a 

<interactive>:2:15: error: Variable not in scope: b 

<interactive>:2:17: error: Variable not in scope: c 

<interactive>:2:19: error: Variable not in scope: d 

<interactive>:2:21: error: Variable not in scope: e 

<interactive>:2:23: error: Variable not in scope: f 

但是,当我检查lastButOne的类型,它看起来像我给它正确的输入类型,即一个列表:

lastButOne :: [a] -> a 

在我的代码中是否有错误,或者我试图错误地使用该程序?

+2

你想提供一个字符串?然后你需要使用'lastButOne“abcdef”'。目前你正在提供一个变量列表'[a,b,c,d,e,f]',但这些变量都没有在任何地方定义过。 – Lee

+2

您认为“变量不在范围内:a”是什么意思? – jwodder

+1

用另一种方式表达:记住''abcdef“'是'['a','b','c','d','e','f']'的糖 - 你需要单引号来命名'Char's。 'a'被拒绝了一个未定义的表达式或“变量”,但'a''被预定义为一个字母的名字。 – Michael

回答

4

的问题是不是类型,那就是没有一个变量abcdef的存在。你不能使用不存在的变量。

+0

我现在看到了。我不知道该程序会将a,b,c ...解释为变量,而不仅仅是字符。 –

+4

@ Zermelo's_Choice如果你想要字符,用'''s围绕它们。或者只是使用字符串文字语法('“abcdef”,这是'['a','b','c','d','e','f']''的快捷键)。 – sepp2k