簡體   English   中英

Haskell 中是否有樹木的標准地圖功能?

[英]Is there a standard map function for trees in Haskell?

我需要編寫一個非遞歸函數來轉換我的樹。 但是我不能對樹木使用我自己的地圖功能。 Haskell 中是否有樹木的標准地圖功能?

data BTree a = Tip a | Bin (BTree a) (BTree a)
exapmeTree = Bin (Bin (Tip [1,2,3,4,5]) (Tip [3,9,7])) (Bin (Tip [6,7,8,9]) (Tip [8,2,1]))
myReverse list = foldl (\acc x -> x : acc) [] list

reverseTree tree = map myReverse tree

由於您自己創建了BTree類型,不,它沒有標准函數。 不過,您可以很容易地自己編寫一個Functor實例。

instance Functor BTree where
  fmap f (Tip a)   = Tip (f a)
  fmap f (Bin l r) = Bin (fmap f l) (fmap f r) 

現在你可以寫reverseTree tree = fmap myReverse tree

請注意, fmap與列表上下文中的map完全相同,但它更通用,這意味着它適用於任何Functor實例。

您可以自己編寫 fmap 函數,如 Rik 所示。

或者你可以使用自動生成的 Functor 實例提供的 fmap 函數。

ghci下測試:

$ ghci
GHCi, version 8.6.5: http://www.haskell.org/ghc/  :? for help
 λ> 
 λ> :set -XDeriveFunctor
 λ> 
 λ> data BTree a = Tip a | Bin (BTree a) (BTree a)  deriving (Eq, Show, Functor)
 λ> 
 λ> exampleTree = Bin (Bin (Tip [1,2,3,4,5]) (Tip [3,9,7])) (Bin (Tip [6,7,8,9]) (Tip [8,2,1]))
 λ> 
 λ> reverseTree = fmap reverse exampleTree
 λ> 
 λ> reverseTree 
 Bin (Bin (Tip [5,4,3,2,1]) (Tip [7,9,3])) (Bin (Tip [9,8,7,6]) (Tip [1,2,8]))
 λ> 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM