小编use*_*968的帖子

在递归函数中使用"Either"进行错误处理

假设一个二叉搜索树,我想在我们尝试插入已经存在的元素时返回错误.有没有办法让这项工作?

data BST2 a = EmptyBST2 | Node2 a (BST2 a) (BST2 a)  deriving Show

insert2 :: a -> Either b (BST2 a) -> Either b (BST2 a)
insert2 elem (Right EmptyBST2) = Right (Node2 elem EmptyBST2 EmptyBST2)
insert2 elem (Right (Node2 root left right))
  | (elem == root) = Left "Error: Element already exist."
  | (elem < root) = (Node2 root (insert2 elem left) right)
  | otherwise = (Node2 root left (insert2 elem right))
Run Code Online (Sandbox Code Playgroud)

注意:我是Haskell的新手.

error-handling binary-tree haskell

2
推荐指数
1
解决办法
462
查看次数

标签 统计

binary-tree ×1

error-handling ×1

haskell ×1