2016-07-26 85 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