【问题标题】:what is the correct way to define an argument in Haskell function在 Haskell 函数中定义参数的正确方法是什么
【发布时间】:2017-01-20 17:48:38
【问题描述】:

我正在使用 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) 您能否就如何重写此代码以获得上述内容提出建议

【问题讨论】:

  • 你的代码中有一些额外的括号,这是清理后的样子:pastebin.com/vpNKvDW7
  • 我认为您实际上需要在没有括号的情况下调用insert 5 Node Leaf 2 Leaf。这在我看来是一个 XY 问题——就好像你需要一些完全不同的东西,但只提到了括号。你到底想达到什么目的?

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    我有一种感觉,你想要的东西是不可能的。使用括号,插入具有类型insert::a -&gt; BinaryTree a -&gt; BinaryTree a(为清楚起见省略了约束)。但是,如果没有括号,类型将是:insert::a -&gt; (BinaryTree a -&gt; a -&gt; BinaryTree a -&gt; BinaryTree a) -&gt; BinaryTree a -&gt; a -&gt; BinaryTree a -&gt; 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)
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2012-06-18
      • 1970-01-01
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2015-12-08
      • 2021-07-18
      • 1970-01-01
      相关资源
      最近更新 更多