Reputation: 1
I try to implement a function that returns a tree with the same structure but with all duplicate values ( nodes )
data BinTreeInt = Void | Node Int BinTreeInt BinTreeInt deriving Show
dupElem :: (Num a) => a -> BinTreeInt -> BinTreeInt
dupElem f Void = Void
dupElem f (Node n l r) = Node (f n) (dupElem f l)(dupElem f r)
I got this error:
P4.hs:382:32:
Could not deduce (a ~ (Int -> Int))
from the context (Num a)
bound by the type signature for
dupElem :: Num a => a -> BinTreeInt -> BinTreeInt
at P4.hs:380:12-51
‘a’ is a rigid type variable bound by
the type signature for
dupElem :: Num a => a -> BinTreeInt -> BinTreeInt
at P4.hs:380:12
Relevant bindings include
f :: a (bound at P4.hs:382:9)
dupElem :: a -> BinTreeInt -> BinTreeInt (bound at P4.hs:381:1)
The function ‘f’ is applied to one argument,
but its type ‘a’ has none
In the first argument of ‘Node’, namely ‘(f n)’
In the expression: Node (f n) (dupElem f l) (dupElem f r)
Failed, modules loaded: none.
Seems to be easy but... Haskell is not my love!
Upvotes: 0
Views: 271
Reputation: 531
According to your function signature "a" is constrained as a Num type but you are calling a as a function over n.
dupElem :: (Num a) => a -> BinTreeInt -> BinTreeInt
So my suggestion would be to change:
Node (f n) (dupElem f l)(dupElem f r)
for
Node f (dupElem f l)(dupElem f r)
as chepner suggested above.
Upvotes: 0
Reputation: 531165
If I understand correctly, you simply want to replace n
with f
, not apply f
as a function to n
.
dupElem :: (Num a) => a -> BinTreeInt -> BinTreeInt
dupElem _ Void = Void
dupElem f (Node n l r) = Node f (dupElem f l)(dupElem f r)
For instance, dupElem 3 (BinTreeInt 1 (BinTreeInt 2 Void Void) Void)
would return (BinTreeInt 3 (BinTreeInt 3 Void Void) Void)
.
Upvotes: 3