Haskell - use it simply or not. Just made a difference, but I don't know why

I found this code in Real World Haskell, p68

data Tree a = Node a (Tree a) (Tree a) | Empty deriving (Show) nodeAreSame (Node a _ _) (Node b _ _) | a == b = Just a nodeAreSame _ _ = Nothing 

My question is: what work did the data constructor Just do? When I delete it, I will get an error, for example

 (in ghci) ...... <Main *> nodeAreSame (Node 3 Empty Empty) (Node 3 Empty Empty)) <interactive>:1:16: No instance for (Num (Maybe a)) ...... 

But when I try to compare the type difference between the version of "Just" and "No Just":

 nodeAreSameJust :: (Eq t) => Tree t -> Tree t -> Maybe t nodeAreSameNoJust :: (Eq a) => Tree (Maybe a) -> Tree (Maybe a) -> Maybe a 

So what is the key here? Does this mean when I put var with type a in node, the function will not output node with type a to get an error?

+4
source share
3 answers

In fact, the absence of Just does not mean that it is poorly printed.

Here's the deal. The code

 nodeAreSame (Node a _ _) (Node b _ _) | a == b = a nodeAreSame _ _ = Nothing 

well printed, provided that a and b are of type Maybe t for some t , since it is type Nothing . Thus, the type system makes this conclusion.

Now that you have a numeric literal such as 3 , it is assumed that it is of type Num s => s , until you pass it to a specific data type (for example, Int or Double ).

So, when he combines these two facts, he assumes the following:

Num (Maybe t) => 3 :: Maybe t .

Since there is no instance for Num (Maybe t) , he complains about this point before getting the opportunity to state that 3 :: Maybe t doesn't make sense.

+12
source

What else do you expect to return, just a ? This will not work because a and Nothing do not match. All function definitions must return the same type. Nothing and Just a , because they are both types of Maybe a .

+3
source

In the version without Just, the element in the tree must be of type Maybe.

I'm not quite sure about the cause of the error, for example, Num (Maybe a). I think the error is more enlightening if you use a string instead of 3.

 *Main> nodeAreSameNoJust (Node "arst" Empty Empty) (Node "arst" Empty Empty) <interactive>:1:24: Couldn't match expected type `Maybe a' against inferred type `[Char]' In the first argument of `Node', namely `"arst"' In the first argument of `nodeAreSameNoJust', namely `(Node "arst" Empty Empty)' In the expression: nodeAreSameNoJust (Node "arst" Empty Empty) (Node "arst" Empty Empty) 

It is more clear here that he expects something like that. May be. In both cases, the second case of the function is Nothing, so the result type is displayed as Maybe. Including Just, the value you use in the tree is then placed in the type of the type. Without this, he expects the result to be the same type as Nothing, since each part of the function must be of the same type.

+2
source

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


All Articles