How does it work when the syntax works?
I researched this solution from GitHub for a problem posed in Haskell from First Principles book. Here is the code
data Nat =
Zero
| Succ Nat deriving (Eq, Show)
integerToNat :: Integer -> Maybe Nat
integerToNat i
| i < 0 = Nothing
| i == 0 = Just Zero
| i > 0 = Just (Succ x) where (Just x) = integerToNat $ i-1
I'm confused about
where (Just x) = integerToNat $ i-1
I thought I could assign an expression to an id in where
. But it looks like it is (Just x)
unpacking the value of the assigned expression and assigning it x
back (Succ x)
.
Can someone please explain why this works?
Haskell context free syntax , contains an entry about the right hand side (rhs) of a function:
rhs & rightarrow;
=
exp [where
decls]
| gdrhs [where
decls]
So we have to take a look at decls
to get the syntax where
. decls
is a sequence decl
s:
decls & rightarrow; {decl 1; ...; decl n}
And a decl
again has two possible rules:
Decl & RightArrow; gendecl
| (funlhs | pat) rhs
This way we can declare patterns (pat) on the left side of the sentence where
. In fact, in where a = 1
, is a
already a sample, which is so to speak. The template consists of one variable. But constructors, alias operators, etc. All are allowed on the left side of the sentence where
.
A template can be a variable, a generic constructor, a qualified constructor, literary, wildcard, list pattern, tuple, irrefutable pattern, etc. Then you can find all the grammar for the patterns here . In short, it works like pattern matching in the head of a function.
source to share