树a的零值->在Haskell [英] Nil Value for Tree a -> a in Haskell

查看:86
本文介绍了树a的零值->在Haskell的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有一棵定义为

data Tree a = Leaf | Node a (Tree a) (Tree a) deriving Show

我知道我可以将Leaf定义为Leaf a.但是我真的只是希望我的节点具有价值.我的问题是,当我执行搜索时,我有一个类型为

I know I can define Leaf to be Leaf a. But I really just want my nodes to have values. My problem is that when I do a search I have a return value function of type

Tree a -> a

由于叶子没有价值,我很困惑如何说如果遇到叶子就什么也不做.我尝试了nil" "' '[]似乎没有任何作用.

Since leafs have no value I am confused how to say if you encounter a leaf do nothing. I tried nil, " ", ' ', [] nothing seems to work.

修改代码

data Tree a = Leaf | Node a (Tree a) (Tree a) deriving Show


breadthFirst   :: Tree a -> [a]
breadthFirst x =  _breadthFirst [x]

_breadthFirst    :: [Tree a] -> [a]
_breadthFirst [] =  []
_breadthFirst xs =  map treeValue xs ++
                _breadthFirst (concat (map immediateChildren xs))

immediateChildren                       :: Tree a -> [Tree a]
immediateChildren (Leaf)              =  []
immediateChildren (Node n left right) =  [left, right]

treeValue                         :: Tree a -> a
treeValue (Leaf)                =  //this is where i need nil
treeValue (Node n left right)   =  n

test = breadthFirst (Node 1 (Node 2 (Node 4 Leaf Leaf) Leaf) (Node 3 Leaf (Node 5 Leaf Leaf)))

main =
  do putStrLn $ show $ test

推荐答案

所以在这种情况下,我的解决方案是使用MaybemapMaybe.简单地说,您可以将treeValue更改为

So my solution in this case would be to use Maybe and mapMaybe. To put it simply, you'd change treeValue to

treeValue                         :: Tree a -> Maybe a
treeValue (Leaf)                =  Nothing
treeValue (Node n left right)   =  Just n

然后使用mapMaybe(来自Data.Maybe)而不是使用map进行组合,它将自动剥离Just,如果它是Nothing,则将其忽略.

Then instead of using map to combine this, use mapMaybe (from Data.Maybe) which will automatically strip away the Just and ignore it if it's Nothing.

 mapMaybe treeValue xs

Voila!

Maybe是Haskell所说的某事可能没有价值"的方式,只是这样定义:

Maybe is Haskell's way of saying "Something might not have a value" and is just defined like this:

data Maybe a = Just a | Nothing

在道德上等同于具有Nullable类型. Haskell只是让您承认一个事实,那就是必须处理"null"的情况.当您需要它们时, Data.Maybe 具有大量有用的功能功能,例如mapMaybe可用.

It's the moral equivalent of having a Nullable type. Haskell just makes you acknowledge the fact that you'll have to handle the case where it is "null". When you need them, Data.Maybe has tons of useful functions, like mapMaybe available.

这篇关于树a的零值->在Haskell的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆