Access Named Fields in a Haskell Function

I defined the data type of the tree in Haskell and its associated 'size' method, which calculates the number of elements in the tree. This worked before, however, I updated the Tree data type to use named fields, as in the following definition:

data Tree a = Empty
 | Leaf {value::a}
 | Node {left :: (Tree a), value :: a, right :: (Tree a)}
 deriving (Eq, Ord, Show)

I found (playing in GHCi) that I can access the named field using a function (n left), for example. However, when I try to use this function, I get an error message:

size :: Tree a -> Int
size Empty    = 0
size (Leaf l)   = 1
size (Node n)   = size (left n) + 1 + size (right n)

GHCi simply says "Not in the field: left" and the equivalent for the right. The Tree definition is in the Tree module and the size definition is in the Main module, but with unnamed fields, I never had a scope problem when it came to accessing variables from the Tree data type.

+3
1

size (Node n) . n .

( ):

size n@(Node _ _ _)   = size (left n) + 1 + size (right n)

:

size n@(Node {})   = size (left n) + 1 + size (right n)

:

size (Node {left=l, right=r})   = size l + 1 + size r

:

size (Node l _ r)   = size l + 1 + size r
+7

Source: https://habr.com/ru/post/1732018/


All Articles