Quora Feeds
Active Member
Mark Harrison
Literate Haskell.
Literate Haskell is a convention for writing Haskell in which all lines except those starting with a “>” symbol are assumed to be comments.
So, if I wanted to define a factorial function in Haskell, I could do so in two parts. In the first part I’ll establish the base case:
> fact 0 = 1
Then I’ll establish the case for a recursive step:
> fact n = n * fact (n-1)
Remember what I wrote about the assumptions about comment lines?
This entire answer is a completely valid Haskell program!
I ought to mention, for completeness, that there are better ways to define the factorial function in Haskell, such as
> newfact n = foldl (*) 1 [1..n]
… but that code, while shorter, is less comprehensible to someone new to the language, since it involves both understanding the way that array construction can be done (the [1..n]) syntax, and the foldl function.
Folding is a powerful concept in functional composition, but a bit outside the scope of this answer. The idea of folding an operator as simple as (*) which is the infix multiplication function, is trivial, and the code above is more normally used as explaining what folding is about than writing factorials
See Questions On Quora
Continue reading...
Literate Haskell.
Literate Haskell is a convention for writing Haskell in which all lines except those starting with a “>” symbol are assumed to be comments.
So, if I wanted to define a factorial function in Haskell, I could do so in two parts. In the first part I’ll establish the base case:
> fact 0 = 1
Then I’ll establish the case for a recursive step:
> fact n = n * fact (n-1)
Remember what I wrote about the assumptions about comment lines?
This entire answer is a completely valid Haskell program!
I ought to mention, for completeness, that there are better ways to define the factorial function in Haskell, such as
> newfact n = foldl (*) 1 [1..n]
… but that code, while shorter, is less comprehensible to someone new to the language, since it involves both understanding the way that array construction can be done (the [1..n]) syntax, and the foldl function.
Folding is a powerful concept in functional composition, but a bit outside the scope of this answer. The idea of folding an operator as simple as (*) which is the infix multiplication function, is trivial, and the code above is more normally used as explaining what folding is about than writing factorials
See Questions On Quora
Continue reading...