2013-03-02 52 views
4

您好我想創建pop和push功能哈斯克爾棧這樣定義:寫作pop和push功能疊加

data mystack = Empty | Elem Char mystack deriving Show 

如果我沒有這個定義限制,我會做俯臥撐這樣

push x mystack = (x:mystack) 

和流行這樣

pop mystack = head mystack 

但是這個限制,我不知道該怎麼imple這些功能。 你能給我一些提示如何做這些請嗎? 我甚至無法用自己的描述寫一個Stack類型。

+3

您絕對需要閱讀[this](http://learnyouahaskell.com/making-our-own-types-and-typeclasses#recursive-data-structures) – 2013-03-02 14:31:43

+2

您還需要檢查您的標識符。遵循'data'關鍵字的標記應該以大寫字母開頭:'data MyStack = Empty | Elem Char MyStack派生(顯示)' – 2013-03-02 14:38:18

+1

ps,你可能沒有意識到它,但你實際上只是重新定義了內置列表。 'MyStack'與'[Char]'(與'String'相同)只是使用不同名稱的值構造函數。 – 2013-03-02 14:39:30

回答

8

提示:這裏是你會如何使用內置列表實現你的堆棧操作:

push :: a -> [a] -> ((),[a]) -- return a tuple containing a 'nothing' and a new stack 
push elem stack = ((), (:) elem stack) 

pop :: [a] -> (a, [a]) -- return a tuple containing the popped element and the new stack 
pop [] = error "Can't pop from an empty stack!" 
pop ((:) x stack) = (x, stack) 

(:) x xs是寫x:xs的另一種方式。

要做到這一點對自己MyStack類型,請注意您Empty實際工作就像[]Elem相當於(:)。我不會給你直接做這個的代碼,因爲爲你自己搞定是有趣的!

+3

如果使用'(:)'而不是中綴':'來表明':'只是一個數據構造函數,那麼這種關係可能會更加明顯,與「Elem」相同,即使語法稍有不同。 – Steve314 2013-03-02 16:10:28

+0

謝謝,你的提示真的幫了很大忙。我終於明白了:) – jason 2013-03-02 21:20:24

+0

當我寫這樣的功能: 'push :: Char - > Stack - > Stack push x Empty =(Element x Empty) push x stack =(Element x stack)' 我得到這個輸入的錯誤:'push''Element'b'Empty' 我得到這個輸出'Element'a'(Element'b'Empty)' 對於這個輸入'push'a'(Element'b'空') 我怎樣才能得到這個輸出:'元素'a'元素'b'空'這個輸入:'推''元素'b'空' 再次感謝您的幫助。 – jason 2013-03-02 21:36:16