3

Firstly, this builds on https://www.schoolofhaskell.com/user/bartosz/understanding-algebras so please read for context if unfamiliar with algebras and recursion schemes.

Say I have a simple expression parser:

data Expr a = ... -- whatever
parse :: String -> Fix Expr
eval :: Algebra Expr (Either String Int)

It may or may not succeed. Example:

cata eval $ parse "3+4" -- Right 7
cata eval $ parse "3+x" -- Left "x not defined"

My question is, if one were to

1) update the parse function to annotate nodes with parse positions

2) prefix error messages with the parsing positions

how could I integrate these new functions below, with those above?

type ParsePositions = (Int,Int)
parse' :: String -> Cofree Expr ParsePositions
prefixError :: ParsePositions -> String -> String

Example usage:

run "3+4" -- Right 7
run "3+x" -- Left "Error parsing [2,2]: x not defined"

Would this be a zygomorphism? Maybe a histomorphism? Both would need some type contortion.

Bonus points: should I be using an elgot algebra to short-circuit on failure seeing evaluation can return Left String?

Golly
  • 1,319
  • 8
  • 18
  • What is `run`? Is it `eval`, or `eval . parse`, or something else? (in general your question should contain code which one can actually compile and run, not just example type signatures). It seems like `run` is parsing and evaluating in one step, which is a mistake - the expression "3+x" is *not* a parse error, it is a semantic error. (you only find out the error when parsing is finished and you are trying to eval). Abandon this idea, as it gains you nothing over separate parsing and evaluation. – user2407038 Oct 22 '16 at 15:02
  • Furthermore, switching to `Cofree` again seems to gain you nothing. What is wrong with `Fix (Expr :+: K ParsePositions)` or `data (:&) f x a = f x :& a; Fix (Expr :& ParsePositions)`? These are isomorphic to `Cofree Expr ParsePositions` but it doesn't require you change the underlying type everywhere in your code. Is there a compelling reason for switching to `Cofree`? Are you looking to use some advanced feature of `Cofree`? If so, which one? – user2407038 Oct 22 '16 at 15:08
  • I think this question is more or less a duplicate of [_How to work with AST with Cofree annotation?_](https://stackoverflow.com/questions/38462563/how-to-work-with-ast-with-cofree-annotation). In my answer to that question I point out that `Cofree` isn't necessarily the best choice for labelling syntax trees and that a plain old functor product will do the job. – Benjamin Hodgson Oct 23 '16 at 14:36

0 Answers0