BartoszMilewski / DaoFP

The Dao of Functional Programming
298 stars 19 forks source link

12.1 Algebras from Endofunctors: x instead of Int? #15

Closed vojkog closed 1 year ago

vojkog commented 1 year ago

Should we have x instead of Int ?

image

BartoszMilewski commented 1 year ago

x replaces the recursive part: We wont the children of Plus to be arbitrary expressions. Val is a terminating node, a leaf. If you replace its argument with x, you'll generate an never-ending data structure.

vojkog commented 1 year ago

Thank you for your answer! I still don't get it. I was thinking of your example from chapter 12.1:

 data ExprF x = ValF x | PlusF x x

 eval :: ExprF Int -> Int
 eval (ValF n) = n
 eval (PlusF m n) = m + n

 pretty :: ExprF String -> String
 pretty (ValF n) = show n
 pretty (PlusF s t) = s ++ " + " ++ t

ghci> In this case, pretty (ValF "Hello") works but with Int as in my previous comment, it would not. Am I missing something?

BartoszMilewski commented 1 year ago

In this case show takes an Int and turns it into a String. Try it with an online Haskell compiler: https://play.haskell.org/saved/badbYBhn

vojkog commented 1 year ago

I see it now. My problem was that the recursive part was not "obvious" to me until a later chapter (12.3), I was focused only on the functorial part, so "fixing Int" seems unnecessary to me. Although you were clear in the chapter intro

data Expr = Val Int | Plus Expr Expr that the recursive part will follow.

Now your answer is perfectly clear. Sorry for bothering you, and Thank you for your patience and beautiful book!