2017-01-20 38 views
0

我正在Haskell中使用二叉搜索樹。什麼是在Haskell函數中定義參數的正確方法

這裏是我寫的

data BinaryTree a = Leaf | Node (BinaryTree a) a (BinaryTree a) 
deriving (Show, Eq) 
    insert :: (Ord a, Eq a) => a -> BinaryTree a -> BinaryTree a 
    insert e (Leaf)= (Node Leaf e Leaf) 
    insert e (Node n1 a n2) 
     | e<a=(Node (insert e n1) a n2) 
     | otherwise = (Node n1 a (insert e n2)) 

的代碼,所以基本上這一塊的代碼將在BST的元素,如果第二個參數被鎖定在括號(如insert 5 (Node Leaf 2 Leaf))內能正常工作,但爲了爲了獲得我想要的,我需要我的程序在兩種情況下工作,當第二個參數在括號內,並且當它不是時(例如insert 5 Node Leaf 2 Leaf) 您能否提供一些關於如何重寫此代碼以獲取內容的建議如上所述

+0

有在你的代碼中的一些額外的括號,這裏是什麼樣子清理:http://pastebin.com/vpNKvDW7 –

+1

我不認爲你實際上_need_調用'插入5節點葉2葉'沒有括號。這對我來說是一個XY問題 - 就好像你需要完全不同的東西,但只提到括號。你真的想用這個來實現什麼? – chi

回答

6

insert 5 Node Leaf 2 Leaf調用01具有5個參數的函數,而不是兩個。如果你想這個工作,唯一的辦法是定義insert採取5個參數。

有沒有辦法使雙方insert 5 Node Leaf 2 Leafinsert 5 (Node Leaf 2 Leaf)工作也沒有辦法讓與更小或更大的樹5參數版本的工作,所以會非常少點吧。

如果你想避免括號,你可以只使用$代替:

insert 5 $ Node Leaf 2 Leaf 
1

我中有你想要的東西是不可能的感覺。帶圓括號的插入類型爲insert::a -> BinaryTree a -> BinaryTree a(爲了清楚起見,約束條件被省略了)。然而,沒有括號的類型將是:insert::a -> (BinaryTree a -> a -> BinaryTree a -> BinaryTree a) -> BinaryTree a -> a -> BinaryTree a -> BinaryTree a

爲了讓你更接近,但是,我可以建議幾個選項。

首先,使用低優先級應用操作$

insert 5 $ Node Leaf 2 Leaf 

其次,你可能會在新的子樹用let,或where條款綁定

let t = Node Leaf 2 Leaf 
in insert 5 t 

insert 5 t 
    where t = Node Leaf 2 Leaf 

三,使用一個參數構造函數,但是這又需要括號或$

node n = Node Leaf n Leaf 
--One of the following 
insert 5 . node $ 2 
(insert 5 . node) 2 
insert 5 (node 2) 
相關問題