在Haskell函数中定义参数的正确方法是什么

时间:2017-01-20 17:48:39

标签: haskell binary-tree binary-search-tree

我正在使用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) 你能否告诉我们如何重写这段代码以获得上述内容

2 个答案:

答案 0 :(得分:6)

insert 5 Node Leaf 2 Leaf使用5个参数调用insert函数,而不是两个。如果您希望这个工作,唯一的方法是定义insert以获取5个参数。

没有办法使insert 5 Node Leaf 2 Leafinsert 5 (Node Leaf 2 Leaf)都工作,也没有办法让5参数版本适用于更小或更大的树,所以对它没什么意义

如果您想避免括号,可以改为使用$

insert 5 $ Node Leaf 2 Leaf

答案 1 :(得分:1)

我有一种感觉,你想要的是不可能的。对于括号,insert具有类型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

其次,您可以使用letwhere子句绑定新的子树

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)
相关问题