How to represent tree with sharing in Haskell

前端 未结 2 1317
南旧
南旧 2021-02-04 05:13

I would like to represent a \"tree\" of the following shape in Haskell:

   /\\                            
  /\\/\\
 /\\/\\/\\
/\\/\\/\\/\\
` ` ` ` `
         


        
2条回答
  •  情深已故
    2021-02-04 05:54

    Perhaps you can represent it simply as a list of leaves and apply the function level by level until you're down to one value, i.e. something like this:

    type Tree a = [a]
    
    propagate :: (a -> a -> a) -> Tree a -> a
    propagate f xs =
      case zipWith f xs (tail xs) of
        [x] -> x
        xs' -> propagate f xs'
    

提交回复
热议问题