3 ms·
How can you approach a problem with logic before knowing what that logic will manipulate? For example you say you'd start writing code to read tokens but a toke
by exdsq 5y ago
How can you approach a problem with logic before knowing what that logic will manipulate? For example you say you'd start writing code to read tokens but a token is a type
- pansa2 5y ago`Token` isn’t a type that a parser has to define - it comes from the previous stage (the lexer), or could even just be `string`. When writing a parser it’s already defined - so do you start the parser by working with the types you already have, or by immediately defining more types? I’d write a parser by first writing code to open a file (for example) to get a collection of tokens, then loop through them and decide what to do for each one. I’d use those decisions to guide my design of the output types. Others, it seems, start by designing the output types up front and use that to guide the design of the program logic.
- eru 5y agoIn something like Haskell, you often write your parsers via parser combinators. So you wouldn't be writing loops (or their Haskell equivalent) at all.
- eru 5y agoI suspect the difference depends on what your types can provide? So in something like Haskell the types are strong enough that going with a types first approach makes a lot of sense. Often once you have the types laid out, many functions will only have a handful of sensible implementations that are even possible at all. In something as primitive as C or Go (before generics) types don't tell you much at all. So laying them out first doesn't give you much at all. You might make a mental (or physical) note of what you are trying to achieve on what data, and then start coding. In Haskell you could express a lot of the content of that note in the types; but in C and Go many or even most things are done via side-effects, and their type system doesn't track these at all.
- shpongled 5y agoIndeed, I do a lot of Rust/ML-style programming, so the type-directed approach comes naturally.