I don’t know haskell syntax, but I know some FP concepts (like algebraic data types, pattern matching, higher-order functions ect).
Can someone explain please, what does this code mean:
data Tree ? = Leaf ? | Fork ? (Tree ?) (Tree ?)
rotateR tree = case tree of
Fork q (Fork p a b) c -> Fork p a (Fork q b c)
As I understand, first line is something like Tree-type declaration (but I don’t understand it exactly). Second line includes pattern matching (I don’t understand as well why do we need to use pattern matching here). And third line does something absolutely unreadable for non-haskell developer. I’ve found definition of Fork as fork (f,g) x = (f x, g x) but I can’t move further anymore.
First of all the data type definition should not contain question marks, but normal letters:
It defines a type
Treethat contains elements of some not further specified typea.The tree is either a
Leaf, containing an element of typea, or it is aFork, containing also an element of typeaand two subtrees. The subtrees areTreestructures that contain elements of typea.Important to note is that Haskell uses parenthesis purely for grouping, like in
2 * (2+3), not to specify calling functions. To call functions, the parameters are just written after the function name, separated with spaces, like insin 30orcompare "abc" "abd".In the
casestatement, the part to the left of->is a pattern match, the part to the right is the functions result in case the tree actually had the form specified on the left. The patternFork q (Fork p a b) cmatches if the tree is aFork(that’s theForkfrom the data type definition) and the first subtree of it is anotherFork. The lowercase letters are all just variables, capturing the different parts of the tree structure matched. Sopwould be the element contained in the subtree,awould be the subtrees first branch andbthe second one.The right side of the
->,Fork p a (Fork q b c), now builds a new tree from these parts matched in the pattern match. The lower case variables are all the tree parts matched on the left, and theForks are the constructors from the data type definition. It build a tree that is aForkand has a second subtree that is also aFork(the part in parenthesis). The remaining pieces of this tree are just the parts of the tree that has been “dissolved” on the left side.