1

I've noticed the following peculiarity in Haskell:

 data Tree a = Empty  | Branch a (Tree a) (Tree a) deriving (Show, Eq)

leaf:: a->Tree a
leaf x = Branch x Empty Empty


findNumL:: Tree a->Integer
findNumL (Empty) = 0
findNumL (Branch x Empty Empty) = 1
findNumL (Branch x left right) = (findNumL left) + (findNumL right)

This is code will run perfectly fine, and it will return the number of leaves in a binary tree. However, if one tries to call the function leaf x instead of Branch x Empty Empty, the pattern recognition breaks down, making the definition of leaf x much less useful than it could be. Is there a way to circumvent this issue and use the leaf in pattern matching?

2
  • I cannot reproduce, probably I don't understand the question. This one works fine findNumL $ Branch "root" (leaf "left") (leaf "right") and so does this findNumL $ leaf "root" Commented Apr 2, 2018 at 0:11
  • @HenriMenke My apologies. I mean in the function definition, if I try findNumL (leaf x) = 1 in the second line of the function definition, the code will not compile. Commented Apr 2, 2018 at 0:13

1 Answer 1

2

You can use the language extension PatternSynonyms

{-# LANGUAGE PatternSynonyms #-}

data Tree a = Empty  | Branch a (Tree a) (Tree a) deriving (Show, Eq)
pattern Leaf a = Branch a Empty Empty

findNumL:: Tree a->Integer
findNumL (Empty) = 0
findNumL (Leaf x) = 1
findNumL (Branch x left right) = (findNumL left) + (findNumL right)

Live example

Sign up to request clarification or add additional context in comments.

9 Comments

does this still keep Leaf as a function a->Tree?
@AndresMejia No, but you don't need it anymore. You can just use Leaf "x" instead of leaf "x".
I'm also still getting an error: "data constructor not in scope"
@AndresMejia Does this happen with the exact example I showed on ideone? ideone.com/YAlxEq
@AndresMejia if you are using GHCI interactively rather than compiling with GHC you may need to :set -XPatternSynonyms
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.