Write a Haskell interpreter in Haskell
A classic programming exercise is to write a Lisp/Scheme interpreter in Lisp/Scheme. The power of the full language can be leveraged to produce an interpreter for a subset of the language.
Is there a similar exercise for Haskell? I'd like to implement a subset of Haskell using Haskell as the engine. Of course it can be done, but are there any online resources available to look at?
Here's the backstory.
I am exploring the idea of using Haskell as a language to explore some of the concepts in a Discrete Structures course I am teaching. For this semester I have settled on Miranda, a smaller language that inspired Haskell. Miranda does about 90% of what I'd like it to do, but Haskell does about 2000%. :)
So my idea is to create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
Pedagogical "language levels" have been used successfully to teach Java and Scheme. By limiting what they can do, you can prevent them from shooting themselves in the foot while they are still mastering the syntax and concepts you are trying to teach. And you can offer better error messages.
haskell functional-programming interpreter
add a comment |
A classic programming exercise is to write a Lisp/Scheme interpreter in Lisp/Scheme. The power of the full language can be leveraged to produce an interpreter for a subset of the language.
Is there a similar exercise for Haskell? I'd like to implement a subset of Haskell using Haskell as the engine. Of course it can be done, but are there any online resources available to look at?
Here's the backstory.
I am exploring the idea of using Haskell as a language to explore some of the concepts in a Discrete Structures course I am teaching. For this semester I have settled on Miranda, a smaller language that inspired Haskell. Miranda does about 90% of what I'd like it to do, but Haskell does about 2000%. :)
So my idea is to create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
Pedagogical "language levels" have been used successfully to teach Java and Scheme. By limiting what they can do, you can prevent them from shooting themselves in the foot while they are still mastering the syntax and concepts you are trying to teach. And you can offer better error messages.
haskell functional-programming interpreter
I have a WIP Haskell dialect implemented with Typing Haskell in Haskell as a base. There's a demo of it here chrisdone.com/toys/duet-delta It's not ready for public open source release, but I could share the source with you if interested.
– Christopher Done
Aug 10 '17 at 11:33
add a comment |
A classic programming exercise is to write a Lisp/Scheme interpreter in Lisp/Scheme. The power of the full language can be leveraged to produce an interpreter for a subset of the language.
Is there a similar exercise for Haskell? I'd like to implement a subset of Haskell using Haskell as the engine. Of course it can be done, but are there any online resources available to look at?
Here's the backstory.
I am exploring the idea of using Haskell as a language to explore some of the concepts in a Discrete Structures course I am teaching. For this semester I have settled on Miranda, a smaller language that inspired Haskell. Miranda does about 90% of what I'd like it to do, but Haskell does about 2000%. :)
So my idea is to create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
Pedagogical "language levels" have been used successfully to teach Java and Scheme. By limiting what they can do, you can prevent them from shooting themselves in the foot while they are still mastering the syntax and concepts you are trying to teach. And you can offer better error messages.
haskell functional-programming interpreter
A classic programming exercise is to write a Lisp/Scheme interpreter in Lisp/Scheme. The power of the full language can be leveraged to produce an interpreter for a subset of the language.
Is there a similar exercise for Haskell? I'd like to implement a subset of Haskell using Haskell as the engine. Of course it can be done, but are there any online resources available to look at?
Here's the backstory.
I am exploring the idea of using Haskell as a language to explore some of the concepts in a Discrete Structures course I am teaching. For this semester I have settled on Miranda, a smaller language that inspired Haskell. Miranda does about 90% of what I'd like it to do, but Haskell does about 2000%. :)
So my idea is to create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
Pedagogical "language levels" have been used successfully to teach Java and Scheme. By limiting what they can do, you can prevent them from shooting themselves in the foot while they are still mastering the syntax and concepts you are trying to teach. And you can offer better error messages.
haskell functional-programming interpreter
haskell functional-programming interpreter
edited Jul 30 '17 at 8:56
Rakete1111
34k980117
34k980117
asked Sep 18 '09 at 17:19
Barry Brown
13.3k116098
13.3k116098
I have a WIP Haskell dialect implemented with Typing Haskell in Haskell as a base. There's a demo of it here chrisdone.com/toys/duet-delta It's not ready for public open source release, but I could share the source with you if interested.
– Christopher Done
Aug 10 '17 at 11:33
add a comment |
I have a WIP Haskell dialect implemented with Typing Haskell in Haskell as a base. There's a demo of it here chrisdone.com/toys/duet-delta It's not ready for public open source release, but I could share the source with you if interested.
– Christopher Done
Aug 10 '17 at 11:33
I have a WIP Haskell dialect implemented with Typing Haskell in Haskell as a base. There's a demo of it here chrisdone.com/toys/duet-delta It's not ready for public open source release, but I could share the source with you if interested.
– Christopher Done
Aug 10 '17 at 11:33
I have a WIP Haskell dialect implemented with Typing Haskell in Haskell as a base. There's a demo of it here chrisdone.com/toys/duet-delta It's not ready for public open source release, but I could share the source with you if interested.
– Christopher Done
Aug 10 '17 at 11:33
add a comment |
15 Answers
15
active
oldest
votes
I love your goal, but it's a big job. A couple of hints:
I've worked on GHC, and you don't want any part of the sources. Hugs is a much simpler, cleaner implementation but unfortunately it's in C.
It's a small piece of the puzzle, but Mark Jones wrote a beautiful paper called Typing Haskell in Haskell which would be a great starting point for your front end.
Good luck! Identifying language levels for Haskell, with supporting evidence from the classroom, would be of great benefit to the community and definitely a publishable result!
2
I can always count on you to have a good response!
– Barry Brown
Sep 18 '09 at 22:46
1
I wonder if the comment about GHC is still accurate. GHC is complex, but it is quite well-documented. In particular, the internalNotes
are helpful in understanding low-level details, and the chapter on GHC in The Architecture of Open-Source Applications provides an excellent high-level overview.
– sjy
Sep 30 '14 at 2:08
add a comment |
There is a complete Haskell parser: http://hackage.haskell.org/package/haskell-src-exts
Once you've parsed it, stripping out or disallowing certain things is easy. I did this for tryhaskell.org to disallow import statements, to support top-level definitions, etc.
Just parse the module:
parseModule :: String -> ParseResult Module
Then you have an AST for a module:
Module SrcLoc ModuleName [ModulePragma] (Maybe WarningText) (Maybe [ExportSpec]) [ImportDecl] [Decl]
The Decl type is extensive: http://hackage.haskell.org/packages/archive/haskell-src-exts/1.9.0/doc/html/Language-Haskell-Exts-Syntax.html#t%3ADecl
All you need to do is define a white-list -- of what declarations, imports, symbols, syntax is available, then walk the AST and throw a "parse error" on anything you don't want them to be aware of yet. You can use the SrcLoc value attached to every node in the AST:
data SrcLoc = SrcLoc
srcFilename :: String
, srcLine :: Int
, srcColumn :: Int
There's no need to re-implement Haskell. If you want to provide more friendly compile errors, just parse the code, filter it, send it to the compiler, and parse the compiler output. If it's a "couldn't match expected type a against inferred a -> b
" then you know it's probably too few arguments to a function.
Unless you really really want to spend time implementing Haskell from scratch or messing with the internals of Hugs, or some dumb implementation, I think you should just filter what gets passed to GHC. That way, if your students want to take their code-base and take it to the next step and write some real fully fledged Haskell code, the transition is transparent.
add a comment |
Do you want to build your interpreter from scratch? Begin with implementing an easier functional language like the lambda calculus or a lisp variant. For the latter there is a quite nice wikibook called Write yourself a Scheme in 48 hours giving a cool and pragmatic introduction into parsing and interpretation techniques.
Interpreting Haskell by hand will be much more complex since you'll have to deal with highly complex features like typeclasses, an extremely powerful type system (type-inference!) and lazy-evaluation (reduction techniques).
So you should define a quite little subset of Haskell to work with and then maybe start by extending the Scheme-example step by step.
Addition:
Note that in Haskell, you have full access to the interpreters API (at least under GHC) including parsers, compilers and of course interpreters.
The package to use is hint (Language.Haskell.*). I have unfortunately neither found online tutorials on this nor tried it out by myself but it looks quite promising.
10
Note that type-inference is actually a really easy, 20-30 line algorithm. it's beautiful in its simplicity. Lazy evaluation is also not so hard to encode. I'd say the difficulty lies in the insane syntax, the pattern matching, and just the large amount of stuff in the language.
– Claudiu
Sep 28 '09 at 17:03
Interesting - Can you post links for the type-inference algos?
– Dario
Sep 28 '09 at 17:34
5
Yeah, check out this free book - cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26 - , it's on page 273 (289 of the pdf). The alg pseudocode is on P296.
– Claudiu
Sep 28 '09 at 22:44
1
There's also an implementation of a (the?) type-inference / checking algorithm in "The Implementation of Functional Programming Languages".
– Phil Armstrong
Aug 15 '11 at 9:58
Type inference with type-classes isn't simple, though.
– Christopher Done
Aug 10 '17 at 10:34
add a comment |
create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
I suggest a simpler (as in less work involved) solution to this problem. Instead of creating a Haskell implementation where you can turn features off, wrap a Haskell compiler with a program that first checks that the code doesn't use any feature you disallow, and then uses the ready-made compiler to compile it.
That would be similar to HLint (and also kind of its opposite):
HLint (formerly Dr. Haskell) reads Haskell programs and suggests changes that hopefully make them easier to read. HLint also makes it easy to disable unwanted suggestions, and to add your own custom suggestions.
- Implement your own HLint "suggestions" to not use the features you don't allow
- Disable all the standard HLint suggestions.
- Make your wrapper run your modified HLint as a first step
- Treat HLint suggestions as errors. That is, if HLint "complained" then the program doesn't proceed to compilation stage
add a comment |
Baskell is a teaching implementation, http://hackage.haskell.org/package/baskell
You might start by picking just, say, the type system to implement. That's about as complicated as an interpreter for Scheme, http://hackage.haskell.org/package/thih
add a comment |
The EHC series of compilers is probably the best bet: it's actively developed and seems to be exactly what you want - a series of small lambda calculi compilers/interpreters culminating in Haskell '98.
But you could also look at the various languages developed in Pierce's Types and Programming Languages, or the Helium interpreter (a crippled Haskell intended for students http://en.wikipedia.org/wiki/Helium_(Haskell)).
add a comment |
If you're looking for a subset of Haskell that's easy to implement, you can do away with type classes and type checking. Without type classes, you don't need type inference to evaluate Haskell code.
I wrote a self-compiling Haskell subset compiler for a Code Golf challenge. It takes Haskell subset code on input and produces C code on output. I'm sorry there isn't a more readable version available; I lifted nested definitions by hand in the process of making it self-compiling.
For a student interested in implementing an interpreter for a subset of Haskell, I would recommend starting with the following features:
Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this.
Function definitions with pattern-matched arguments and guards. Only worry about variable, cons, nil, and
_
patterns.Simple expression syntax:
Integer literals
Character literals
(nil)
Function application (left associative)
Infix
:
(cons, right associative)Parenthesis
Variable names
Function names
More concretely, write an interpreter that can run this:
-- tail :: [a] -> [a]
tail (_:xs) = xs
-- append :: [a] -> [a] -> [a]
append ys = ys
append (x:xs) ys = x : append xs ys
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _ _ =
-- showList :: (a -> String) -> [a] -> String
showList _ = '[' : ']' :
showList show (x:xs) = '[' : append (show x) (showItems show xs)
-- showItems :: (a -> String) -> [a] -> String
showItems show = ']' :
showItems show (x:xs) = ',' : append (show x) (showItems show xs)
-- fibs :: [Int]
fibs = 0 : 1 : zipWith add fibs (tail fibs)
-- main :: String
main = showList showInt (take 40 fibs)
Type checking is a crucial feature of Haskell. However, going from nothing to a type-checking Haskell compiler is very difficult. If you start by writing an interpreter for the above, adding type checking to it should be less daunting.
"Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this." This may not be true. See Naylor's article in haskell.org/wikiupload/0/0a/TMR-Issue10.pdf for more info on implementing a lazy interpreter in Haskell.
– Jared Updike
Mar 6 '14 at 18:30
add a comment |
You might look at Happy (a yacc-like parser in Haskell) which has a Haskell parser.
add a comment |
This might be a good idea - make a tiny version of NetLogo in Haskell. Here is the tiny interpreter.
The links are dead. Any chance this content still exists somewhere else? I'd be curious...
– Nicolas Payette
Dec 9 '12 at 5:22
hmm it was a blog post and I have no idea what keywords to use to search for it. A good lesson to include more substantial info when providing a link...
– Claudiu
Dec 9 '12 at 23:22
1
A Google search for "netlogo haskell" turns up... this question. Anyway, no big deal. Thanks!
– Nicolas Payette
Dec 10 '12 at 18:40
add a comment |
see if helium would make a better base to build upon than standard haskell.
add a comment |
Uhc/Ehc is a series of compilers enabling/disabling various Haskell features.
http://www.cs.uu.nl/wiki/Ehc/WebHome#What_is_UHC_And_EHC
add a comment |
I've been told that Idris has a fairly compact parser, not sure if it's really suitable for alteration, but it's written in Haskell.
add a comment |
Andrej Bauer's Programming Language Zoo has a small implementation of a purely functional programming language somewhat cheekily named "minihaskell". It is about 700 lines of OCaml, so very easy to digest.
The site also contains toy versions of ML-style, Prolog-style and OO programming languages.
add a comment |
Don't you think it would be easier to take the GHC sources and strip out what you don't want, than it would be to write your own Haskell interpreter from scratch? Generally speaking, there should be a lot less effort involved in removing features as opposed to creating/adding features.
GHC is written in Haskell anyway, so technically that stays with your question of a Haskell interpreter written in Haskell.
It probably wouldn't be too hard to make the whole thing statically linked and then only distribute your customized GHCi, so that the students can't load other Haskell source modules. As to how much work it would take to prevent them from loading other Haskell object files, I have no idea. You might want to disable FFI too, if you have a bunch of cheaters in your classes :)
1
This is not as easy as it sounds, as many features depend on others. But perhaps the OP just wants to not import Prelude and instead provide his own. Most of Haskell that you see are normal functions, not specific features of the runtime. (But of course, a lot are.)
– jrockway
Sep 23 '09 at 7:44
add a comment |
The reason why there are so many LISP interpreters is that LISP is basically a predecessor of JSON: a simple format to encode data. This makes the frontend part quite easy to handle. Compared to that, Haskell, especially with Language Extensions, is not the easiest language to parse.
These are some syntactical constructs that sound tricky to get right:
- operators with configurable precedence, associativity, and fixity,
- nested comments
- layout rule
- pattern syntax
do
- blocks and desugaring to monadic code
Each of these, except maybe the operators, could be tackled by students after their Compiler Construction Course, but it would take the focus away from how Haskell actually works. In addition to that, you might not want to implement all syntactical constructs of Haskell directly, but instead implement passes to get rid of them. Which brings us to the literal core of the issue, pun fully intended.
My suggestion is to implement typechecking and an interpreter for Core
instead of full Haskell. Both of these tasks are quite intricate by themselves already.
This language, while still a strongly typed functional language, is way less complicated to deal with in terms of optimization and code generation.
However, it is still independent from the underlying machine.
Therefore, GHC uses it as an intermediary language and translates most syntaxical constructs of Haskell into it.
Additionally, you should not shy away from using GHC's (or another compiler's) frontend.
I'd not consider that as cheating since custom LISPs use the host LISP system's parser (at least during bootstrapping). Cleaning up Core
snippets and presenting them to students, along with the original code, should allow you to give an overview of what the frontend does, and why it is preferable to not reimplement it.
Here are a few links to the documentation of Core
as used in GHC:
- System FC: equality constraints and coercions
- GHC/As a library
- The
Core
type
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1445827%2fwrite-a-haskell-interpreter-in-haskell%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
15 Answers
15
active
oldest
votes
15 Answers
15
active
oldest
votes
active
oldest
votes
active
oldest
votes
I love your goal, but it's a big job. A couple of hints:
I've worked on GHC, and you don't want any part of the sources. Hugs is a much simpler, cleaner implementation but unfortunately it's in C.
It's a small piece of the puzzle, but Mark Jones wrote a beautiful paper called Typing Haskell in Haskell which would be a great starting point for your front end.
Good luck! Identifying language levels for Haskell, with supporting evidence from the classroom, would be of great benefit to the community and definitely a publishable result!
2
I can always count on you to have a good response!
– Barry Brown
Sep 18 '09 at 22:46
1
I wonder if the comment about GHC is still accurate. GHC is complex, but it is quite well-documented. In particular, the internalNotes
are helpful in understanding low-level details, and the chapter on GHC in The Architecture of Open-Source Applications provides an excellent high-level overview.
– sjy
Sep 30 '14 at 2:08
add a comment |
I love your goal, but it's a big job. A couple of hints:
I've worked on GHC, and you don't want any part of the sources. Hugs is a much simpler, cleaner implementation but unfortunately it's in C.
It's a small piece of the puzzle, but Mark Jones wrote a beautiful paper called Typing Haskell in Haskell which would be a great starting point for your front end.
Good luck! Identifying language levels for Haskell, with supporting evidence from the classroom, would be of great benefit to the community and definitely a publishable result!
2
I can always count on you to have a good response!
– Barry Brown
Sep 18 '09 at 22:46
1
I wonder if the comment about GHC is still accurate. GHC is complex, but it is quite well-documented. In particular, the internalNotes
are helpful in understanding low-level details, and the chapter on GHC in The Architecture of Open-Source Applications provides an excellent high-level overview.
– sjy
Sep 30 '14 at 2:08
add a comment |
I love your goal, but it's a big job. A couple of hints:
I've worked on GHC, and you don't want any part of the sources. Hugs is a much simpler, cleaner implementation but unfortunately it's in C.
It's a small piece of the puzzle, but Mark Jones wrote a beautiful paper called Typing Haskell in Haskell which would be a great starting point for your front end.
Good luck! Identifying language levels for Haskell, with supporting evidence from the classroom, would be of great benefit to the community and definitely a publishable result!
I love your goal, but it's a big job. A couple of hints:
I've worked on GHC, and you don't want any part of the sources. Hugs is a much simpler, cleaner implementation but unfortunately it's in C.
It's a small piece of the puzzle, but Mark Jones wrote a beautiful paper called Typing Haskell in Haskell which would be a great starting point for your front end.
Good luck! Identifying language levels for Haskell, with supporting evidence from the classroom, would be of great benefit to the community and definitely a publishable result!
answered Sep 18 '09 at 22:31
Norman Ramsey
163k52320500
163k52320500
2
I can always count on you to have a good response!
– Barry Brown
Sep 18 '09 at 22:46
1
I wonder if the comment about GHC is still accurate. GHC is complex, but it is quite well-documented. In particular, the internalNotes
are helpful in understanding low-level details, and the chapter on GHC in The Architecture of Open-Source Applications provides an excellent high-level overview.
– sjy
Sep 30 '14 at 2:08
add a comment |
2
I can always count on you to have a good response!
– Barry Brown
Sep 18 '09 at 22:46
1
I wonder if the comment about GHC is still accurate. GHC is complex, but it is quite well-documented. In particular, the internalNotes
are helpful in understanding low-level details, and the chapter on GHC in The Architecture of Open-Source Applications provides an excellent high-level overview.
– sjy
Sep 30 '14 at 2:08
2
2
I can always count on you to have a good response!
– Barry Brown
Sep 18 '09 at 22:46
I can always count on you to have a good response!
– Barry Brown
Sep 18 '09 at 22:46
1
1
I wonder if the comment about GHC is still accurate. GHC is complex, but it is quite well-documented. In particular, the internal
Notes
are helpful in understanding low-level details, and the chapter on GHC in The Architecture of Open-Source Applications provides an excellent high-level overview.– sjy
Sep 30 '14 at 2:08
I wonder if the comment about GHC is still accurate. GHC is complex, but it is quite well-documented. In particular, the internal
Notes
are helpful in understanding low-level details, and the chapter on GHC in The Architecture of Open-Source Applications provides an excellent high-level overview.– sjy
Sep 30 '14 at 2:08
add a comment |
There is a complete Haskell parser: http://hackage.haskell.org/package/haskell-src-exts
Once you've parsed it, stripping out or disallowing certain things is easy. I did this for tryhaskell.org to disallow import statements, to support top-level definitions, etc.
Just parse the module:
parseModule :: String -> ParseResult Module
Then you have an AST for a module:
Module SrcLoc ModuleName [ModulePragma] (Maybe WarningText) (Maybe [ExportSpec]) [ImportDecl] [Decl]
The Decl type is extensive: http://hackage.haskell.org/packages/archive/haskell-src-exts/1.9.0/doc/html/Language-Haskell-Exts-Syntax.html#t%3ADecl
All you need to do is define a white-list -- of what declarations, imports, symbols, syntax is available, then walk the AST and throw a "parse error" on anything you don't want them to be aware of yet. You can use the SrcLoc value attached to every node in the AST:
data SrcLoc = SrcLoc
srcFilename :: String
, srcLine :: Int
, srcColumn :: Int
There's no need to re-implement Haskell. If you want to provide more friendly compile errors, just parse the code, filter it, send it to the compiler, and parse the compiler output. If it's a "couldn't match expected type a against inferred a -> b
" then you know it's probably too few arguments to a function.
Unless you really really want to spend time implementing Haskell from scratch or messing with the internals of Hugs, or some dumb implementation, I think you should just filter what gets passed to GHC. That way, if your students want to take their code-base and take it to the next step and write some real fully fledged Haskell code, the transition is transparent.
add a comment |
There is a complete Haskell parser: http://hackage.haskell.org/package/haskell-src-exts
Once you've parsed it, stripping out or disallowing certain things is easy. I did this for tryhaskell.org to disallow import statements, to support top-level definitions, etc.
Just parse the module:
parseModule :: String -> ParseResult Module
Then you have an AST for a module:
Module SrcLoc ModuleName [ModulePragma] (Maybe WarningText) (Maybe [ExportSpec]) [ImportDecl] [Decl]
The Decl type is extensive: http://hackage.haskell.org/packages/archive/haskell-src-exts/1.9.0/doc/html/Language-Haskell-Exts-Syntax.html#t%3ADecl
All you need to do is define a white-list -- of what declarations, imports, symbols, syntax is available, then walk the AST and throw a "parse error" on anything you don't want them to be aware of yet. You can use the SrcLoc value attached to every node in the AST:
data SrcLoc = SrcLoc
srcFilename :: String
, srcLine :: Int
, srcColumn :: Int
There's no need to re-implement Haskell. If you want to provide more friendly compile errors, just parse the code, filter it, send it to the compiler, and parse the compiler output. If it's a "couldn't match expected type a against inferred a -> b
" then you know it's probably too few arguments to a function.
Unless you really really want to spend time implementing Haskell from scratch or messing with the internals of Hugs, or some dumb implementation, I think you should just filter what gets passed to GHC. That way, if your students want to take their code-base and take it to the next step and write some real fully fledged Haskell code, the transition is transparent.
add a comment |
There is a complete Haskell parser: http://hackage.haskell.org/package/haskell-src-exts
Once you've parsed it, stripping out or disallowing certain things is easy. I did this for tryhaskell.org to disallow import statements, to support top-level definitions, etc.
Just parse the module:
parseModule :: String -> ParseResult Module
Then you have an AST for a module:
Module SrcLoc ModuleName [ModulePragma] (Maybe WarningText) (Maybe [ExportSpec]) [ImportDecl] [Decl]
The Decl type is extensive: http://hackage.haskell.org/packages/archive/haskell-src-exts/1.9.0/doc/html/Language-Haskell-Exts-Syntax.html#t%3ADecl
All you need to do is define a white-list -- of what declarations, imports, symbols, syntax is available, then walk the AST and throw a "parse error" on anything you don't want them to be aware of yet. You can use the SrcLoc value attached to every node in the AST:
data SrcLoc = SrcLoc
srcFilename :: String
, srcLine :: Int
, srcColumn :: Int
There's no need to re-implement Haskell. If you want to provide more friendly compile errors, just parse the code, filter it, send it to the compiler, and parse the compiler output. If it's a "couldn't match expected type a against inferred a -> b
" then you know it's probably too few arguments to a function.
Unless you really really want to spend time implementing Haskell from scratch or messing with the internals of Hugs, or some dumb implementation, I think you should just filter what gets passed to GHC. That way, if your students want to take their code-base and take it to the next step and write some real fully fledged Haskell code, the transition is transparent.
There is a complete Haskell parser: http://hackage.haskell.org/package/haskell-src-exts
Once you've parsed it, stripping out or disallowing certain things is easy. I did this for tryhaskell.org to disallow import statements, to support top-level definitions, etc.
Just parse the module:
parseModule :: String -> ParseResult Module
Then you have an AST for a module:
Module SrcLoc ModuleName [ModulePragma] (Maybe WarningText) (Maybe [ExportSpec]) [ImportDecl] [Decl]
The Decl type is extensive: http://hackage.haskell.org/packages/archive/haskell-src-exts/1.9.0/doc/html/Language-Haskell-Exts-Syntax.html#t%3ADecl
All you need to do is define a white-list -- of what declarations, imports, symbols, syntax is available, then walk the AST and throw a "parse error" on anything you don't want them to be aware of yet. You can use the SrcLoc value attached to every node in the AST:
data SrcLoc = SrcLoc
srcFilename :: String
, srcLine :: Int
, srcColumn :: Int
There's no need to re-implement Haskell. If you want to provide more friendly compile errors, just parse the code, filter it, send it to the compiler, and parse the compiler output. If it's a "couldn't match expected type a against inferred a -> b
" then you know it's probably too few arguments to a function.
Unless you really really want to spend time implementing Haskell from scratch or messing with the internals of Hugs, or some dumb implementation, I think you should just filter what gets passed to GHC. That way, if your students want to take their code-base and take it to the next step and write some real fully fledged Haskell code, the transition is transparent.
answered Jul 17 '10 at 18:09
Christopher Done
3,98632635
3,98632635
add a comment |
add a comment |
Do you want to build your interpreter from scratch? Begin with implementing an easier functional language like the lambda calculus or a lisp variant. For the latter there is a quite nice wikibook called Write yourself a Scheme in 48 hours giving a cool and pragmatic introduction into parsing and interpretation techniques.
Interpreting Haskell by hand will be much more complex since you'll have to deal with highly complex features like typeclasses, an extremely powerful type system (type-inference!) and lazy-evaluation (reduction techniques).
So you should define a quite little subset of Haskell to work with and then maybe start by extending the Scheme-example step by step.
Addition:
Note that in Haskell, you have full access to the interpreters API (at least under GHC) including parsers, compilers and of course interpreters.
The package to use is hint (Language.Haskell.*). I have unfortunately neither found online tutorials on this nor tried it out by myself but it looks quite promising.
10
Note that type-inference is actually a really easy, 20-30 line algorithm. it's beautiful in its simplicity. Lazy evaluation is also not so hard to encode. I'd say the difficulty lies in the insane syntax, the pattern matching, and just the large amount of stuff in the language.
– Claudiu
Sep 28 '09 at 17:03
Interesting - Can you post links for the type-inference algos?
– Dario
Sep 28 '09 at 17:34
5
Yeah, check out this free book - cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26 - , it's on page 273 (289 of the pdf). The alg pseudocode is on P296.
– Claudiu
Sep 28 '09 at 22:44
1
There's also an implementation of a (the?) type-inference / checking algorithm in "The Implementation of Functional Programming Languages".
– Phil Armstrong
Aug 15 '11 at 9:58
Type inference with type-classes isn't simple, though.
– Christopher Done
Aug 10 '17 at 10:34
add a comment |
Do you want to build your interpreter from scratch? Begin with implementing an easier functional language like the lambda calculus or a lisp variant. For the latter there is a quite nice wikibook called Write yourself a Scheme in 48 hours giving a cool and pragmatic introduction into parsing and interpretation techniques.
Interpreting Haskell by hand will be much more complex since you'll have to deal with highly complex features like typeclasses, an extremely powerful type system (type-inference!) and lazy-evaluation (reduction techniques).
So you should define a quite little subset of Haskell to work with and then maybe start by extending the Scheme-example step by step.
Addition:
Note that in Haskell, you have full access to the interpreters API (at least under GHC) including parsers, compilers and of course interpreters.
The package to use is hint (Language.Haskell.*). I have unfortunately neither found online tutorials on this nor tried it out by myself but it looks quite promising.
10
Note that type-inference is actually a really easy, 20-30 line algorithm. it's beautiful in its simplicity. Lazy evaluation is also not so hard to encode. I'd say the difficulty lies in the insane syntax, the pattern matching, and just the large amount of stuff in the language.
– Claudiu
Sep 28 '09 at 17:03
Interesting - Can you post links for the type-inference algos?
– Dario
Sep 28 '09 at 17:34
5
Yeah, check out this free book - cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26 - , it's on page 273 (289 of the pdf). The alg pseudocode is on P296.
– Claudiu
Sep 28 '09 at 22:44
1
There's also an implementation of a (the?) type-inference / checking algorithm in "The Implementation of Functional Programming Languages".
– Phil Armstrong
Aug 15 '11 at 9:58
Type inference with type-classes isn't simple, though.
– Christopher Done
Aug 10 '17 at 10:34
add a comment |
Do you want to build your interpreter from scratch? Begin with implementing an easier functional language like the lambda calculus or a lisp variant. For the latter there is a quite nice wikibook called Write yourself a Scheme in 48 hours giving a cool and pragmatic introduction into parsing and interpretation techniques.
Interpreting Haskell by hand will be much more complex since you'll have to deal with highly complex features like typeclasses, an extremely powerful type system (type-inference!) and lazy-evaluation (reduction techniques).
So you should define a quite little subset of Haskell to work with and then maybe start by extending the Scheme-example step by step.
Addition:
Note that in Haskell, you have full access to the interpreters API (at least under GHC) including parsers, compilers and of course interpreters.
The package to use is hint (Language.Haskell.*). I have unfortunately neither found online tutorials on this nor tried it out by myself but it looks quite promising.
Do you want to build your interpreter from scratch? Begin with implementing an easier functional language like the lambda calculus or a lisp variant. For the latter there is a quite nice wikibook called Write yourself a Scheme in 48 hours giving a cool and pragmatic introduction into parsing and interpretation techniques.
Interpreting Haskell by hand will be much more complex since you'll have to deal with highly complex features like typeclasses, an extremely powerful type system (type-inference!) and lazy-evaluation (reduction techniques).
So you should define a quite little subset of Haskell to work with and then maybe start by extending the Scheme-example step by step.
Addition:
Note that in Haskell, you have full access to the interpreters API (at least under GHC) including parsers, compilers and of course interpreters.
The package to use is hint (Language.Haskell.*). I have unfortunately neither found online tutorials on this nor tried it out by myself but it looks quite promising.
answered Sep 18 '09 at 17:36
Dario
39.8k681117
39.8k681117
10
Note that type-inference is actually a really easy, 20-30 line algorithm. it's beautiful in its simplicity. Lazy evaluation is also not so hard to encode. I'd say the difficulty lies in the insane syntax, the pattern matching, and just the large amount of stuff in the language.
– Claudiu
Sep 28 '09 at 17:03
Interesting - Can you post links for the type-inference algos?
– Dario
Sep 28 '09 at 17:34
5
Yeah, check out this free book - cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26 - , it's on page 273 (289 of the pdf). The alg pseudocode is on P296.
– Claudiu
Sep 28 '09 at 22:44
1
There's also an implementation of a (the?) type-inference / checking algorithm in "The Implementation of Functional Programming Languages".
– Phil Armstrong
Aug 15 '11 at 9:58
Type inference with type-classes isn't simple, though.
– Christopher Done
Aug 10 '17 at 10:34
add a comment |
10
Note that type-inference is actually a really easy, 20-30 line algorithm. it's beautiful in its simplicity. Lazy evaluation is also not so hard to encode. I'd say the difficulty lies in the insane syntax, the pattern matching, and just the large amount of stuff in the language.
– Claudiu
Sep 28 '09 at 17:03
Interesting - Can you post links for the type-inference algos?
– Dario
Sep 28 '09 at 17:34
5
Yeah, check out this free book - cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26 - , it's on page 273 (289 of the pdf). The alg pseudocode is on P296.
– Claudiu
Sep 28 '09 at 22:44
1
There's also an implementation of a (the?) type-inference / checking algorithm in "The Implementation of Functional Programming Languages".
– Phil Armstrong
Aug 15 '11 at 9:58
Type inference with type-classes isn't simple, though.
– Christopher Done
Aug 10 '17 at 10:34
10
10
Note that type-inference is actually a really easy, 20-30 line algorithm. it's beautiful in its simplicity. Lazy evaluation is also not so hard to encode. I'd say the difficulty lies in the insane syntax, the pattern matching, and just the large amount of stuff in the language.
– Claudiu
Sep 28 '09 at 17:03
Note that type-inference is actually a really easy, 20-30 line algorithm. it's beautiful in its simplicity. Lazy evaluation is also not so hard to encode. I'd say the difficulty lies in the insane syntax, the pattern matching, and just the large amount of stuff in the language.
– Claudiu
Sep 28 '09 at 17:03
Interesting - Can you post links for the type-inference algos?
– Dario
Sep 28 '09 at 17:34
Interesting - Can you post links for the type-inference algos?
– Dario
Sep 28 '09 at 17:34
5
5
Yeah, check out this free book - cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26 - , it's on page 273 (289 of the pdf). The alg pseudocode is on P296.
– Claudiu
Sep 28 '09 at 22:44
Yeah, check out this free book - cs.brown.edu/~sk/Publications/Books/ProgLangs/2007-04-26 - , it's on page 273 (289 of the pdf). The alg pseudocode is on P296.
– Claudiu
Sep 28 '09 at 22:44
1
1
There's also an implementation of a (the?) type-inference / checking algorithm in "The Implementation of Functional Programming Languages".
– Phil Armstrong
Aug 15 '11 at 9:58
There's also an implementation of a (the?) type-inference / checking algorithm in "The Implementation of Functional Programming Languages".
– Phil Armstrong
Aug 15 '11 at 9:58
Type inference with type-classes isn't simple, though.
– Christopher Done
Aug 10 '17 at 10:34
Type inference with type-classes isn't simple, though.
– Christopher Done
Aug 10 '17 at 10:34
add a comment |
create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
I suggest a simpler (as in less work involved) solution to this problem. Instead of creating a Haskell implementation where you can turn features off, wrap a Haskell compiler with a program that first checks that the code doesn't use any feature you disallow, and then uses the ready-made compiler to compile it.
That would be similar to HLint (and also kind of its opposite):
HLint (formerly Dr. Haskell) reads Haskell programs and suggests changes that hopefully make them easier to read. HLint also makes it easy to disable unwanted suggestions, and to add your own custom suggestions.
- Implement your own HLint "suggestions" to not use the features you don't allow
- Disable all the standard HLint suggestions.
- Make your wrapper run your modified HLint as a first step
- Treat HLint suggestions as errors. That is, if HLint "complained" then the program doesn't proceed to compilation stage
add a comment |
create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
I suggest a simpler (as in less work involved) solution to this problem. Instead of creating a Haskell implementation where you can turn features off, wrap a Haskell compiler with a program that first checks that the code doesn't use any feature you disallow, and then uses the ready-made compiler to compile it.
That would be similar to HLint (and also kind of its opposite):
HLint (formerly Dr. Haskell) reads Haskell programs and suggests changes that hopefully make them easier to read. HLint also makes it easy to disable unwanted suggestions, and to add your own custom suggestions.
- Implement your own HLint "suggestions" to not use the features you don't allow
- Disable all the standard HLint suggestions.
- Make your wrapper run your modified HLint as a first step
- Treat HLint suggestions as errors. That is, if HLint "complained" then the program doesn't proceed to compilation stage
add a comment |
create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
I suggest a simpler (as in less work involved) solution to this problem. Instead of creating a Haskell implementation where you can turn features off, wrap a Haskell compiler with a program that first checks that the code doesn't use any feature you disallow, and then uses the ready-made compiler to compile it.
That would be similar to HLint (and also kind of its opposite):
HLint (formerly Dr. Haskell) reads Haskell programs and suggests changes that hopefully make them easier to read. HLint also makes it easy to disable unwanted suggestions, and to add your own custom suggestions.
- Implement your own HLint "suggestions" to not use the features you don't allow
- Disable all the standard HLint suggestions.
- Make your wrapper run your modified HLint as a first step
- Treat HLint suggestions as errors. That is, if HLint "complained" then the program doesn't proceed to compilation stage
create a language that has exactly the features of Haskell that I'd like and disallows everything else. As the students progress, I can selectively "turn on" various features once they've mastered the basics.
I suggest a simpler (as in less work involved) solution to this problem. Instead of creating a Haskell implementation where you can turn features off, wrap a Haskell compiler with a program that first checks that the code doesn't use any feature you disallow, and then uses the ready-made compiler to compile it.
That would be similar to HLint (and also kind of its opposite):
HLint (formerly Dr. Haskell) reads Haskell programs and suggests changes that hopefully make them easier to read. HLint also makes it easy to disable unwanted suggestions, and to add your own custom suggestions.
- Implement your own HLint "suggestions" to not use the features you don't allow
- Disable all the standard HLint suggestions.
- Make your wrapper run your modified HLint as a first step
- Treat HLint suggestions as errors. That is, if HLint "complained" then the program doesn't proceed to compilation stage
edited Nov 12 at 12:03
Rodrigo Silva
32
32
answered Sep 18 '09 at 21:31
yairchu
15.4k75894
15.4k75894
add a comment |
add a comment |
Baskell is a teaching implementation, http://hackage.haskell.org/package/baskell
You might start by picking just, say, the type system to implement. That's about as complicated as an interpreter for Scheme, http://hackage.haskell.org/package/thih
add a comment |
Baskell is a teaching implementation, http://hackage.haskell.org/package/baskell
You might start by picking just, say, the type system to implement. That's about as complicated as an interpreter for Scheme, http://hackage.haskell.org/package/thih
add a comment |
Baskell is a teaching implementation, http://hackage.haskell.org/package/baskell
You might start by picking just, say, the type system to implement. That's about as complicated as an interpreter for Scheme, http://hackage.haskell.org/package/thih
Baskell is a teaching implementation, http://hackage.haskell.org/package/baskell
You might start by picking just, say, the type system to implement. That's about as complicated as an interpreter for Scheme, http://hackage.haskell.org/package/thih
answered Sep 19 '09 at 16:20
Don Stewart
128k31333447
128k31333447
add a comment |
add a comment |
The EHC series of compilers is probably the best bet: it's actively developed and seems to be exactly what you want - a series of small lambda calculi compilers/interpreters culminating in Haskell '98.
But you could also look at the various languages developed in Pierce's Types and Programming Languages, or the Helium interpreter (a crippled Haskell intended for students http://en.wikipedia.org/wiki/Helium_(Haskell)).
add a comment |
The EHC series of compilers is probably the best bet: it's actively developed and seems to be exactly what you want - a series of small lambda calculi compilers/interpreters culminating in Haskell '98.
But you could also look at the various languages developed in Pierce's Types and Programming Languages, or the Helium interpreter (a crippled Haskell intended for students http://en.wikipedia.org/wiki/Helium_(Haskell)).
add a comment |
The EHC series of compilers is probably the best bet: it's actively developed and seems to be exactly what you want - a series of small lambda calculi compilers/interpreters culminating in Haskell '98.
But you could also look at the various languages developed in Pierce's Types and Programming Languages, or the Helium interpreter (a crippled Haskell intended for students http://en.wikipedia.org/wiki/Helium_(Haskell)).
The EHC series of compilers is probably the best bet: it's actively developed and seems to be exactly what you want - a series of small lambda calculi compilers/interpreters culminating in Haskell '98.
But you could also look at the various languages developed in Pierce's Types and Programming Languages, or the Helium interpreter (a crippled Haskell intended for students http://en.wikipedia.org/wiki/Helium_(Haskell)).
answered Dec 21 '09 at 16:15
community wiki
gwern
add a comment |
add a comment |
If you're looking for a subset of Haskell that's easy to implement, you can do away with type classes and type checking. Without type classes, you don't need type inference to evaluate Haskell code.
I wrote a self-compiling Haskell subset compiler for a Code Golf challenge. It takes Haskell subset code on input and produces C code on output. I'm sorry there isn't a more readable version available; I lifted nested definitions by hand in the process of making it self-compiling.
For a student interested in implementing an interpreter for a subset of Haskell, I would recommend starting with the following features:
Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this.
Function definitions with pattern-matched arguments and guards. Only worry about variable, cons, nil, and
_
patterns.Simple expression syntax:
Integer literals
Character literals
(nil)
Function application (left associative)
Infix
:
(cons, right associative)Parenthesis
Variable names
Function names
More concretely, write an interpreter that can run this:
-- tail :: [a] -> [a]
tail (_:xs) = xs
-- append :: [a] -> [a] -> [a]
append ys = ys
append (x:xs) ys = x : append xs ys
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _ _ =
-- showList :: (a -> String) -> [a] -> String
showList _ = '[' : ']' :
showList show (x:xs) = '[' : append (show x) (showItems show xs)
-- showItems :: (a -> String) -> [a] -> String
showItems show = ']' :
showItems show (x:xs) = ',' : append (show x) (showItems show xs)
-- fibs :: [Int]
fibs = 0 : 1 : zipWith add fibs (tail fibs)
-- main :: String
main = showList showInt (take 40 fibs)
Type checking is a crucial feature of Haskell. However, going from nothing to a type-checking Haskell compiler is very difficult. If you start by writing an interpreter for the above, adding type checking to it should be less daunting.
"Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this." This may not be true. See Naylor's article in haskell.org/wikiupload/0/0a/TMR-Issue10.pdf for more info on implementing a lazy interpreter in Haskell.
– Jared Updike
Mar 6 '14 at 18:30
add a comment |
If you're looking for a subset of Haskell that's easy to implement, you can do away with type classes and type checking. Without type classes, you don't need type inference to evaluate Haskell code.
I wrote a self-compiling Haskell subset compiler for a Code Golf challenge. It takes Haskell subset code on input and produces C code on output. I'm sorry there isn't a more readable version available; I lifted nested definitions by hand in the process of making it self-compiling.
For a student interested in implementing an interpreter for a subset of Haskell, I would recommend starting with the following features:
Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this.
Function definitions with pattern-matched arguments and guards. Only worry about variable, cons, nil, and
_
patterns.Simple expression syntax:
Integer literals
Character literals
(nil)
Function application (left associative)
Infix
:
(cons, right associative)Parenthesis
Variable names
Function names
More concretely, write an interpreter that can run this:
-- tail :: [a] -> [a]
tail (_:xs) = xs
-- append :: [a] -> [a] -> [a]
append ys = ys
append (x:xs) ys = x : append xs ys
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _ _ =
-- showList :: (a -> String) -> [a] -> String
showList _ = '[' : ']' :
showList show (x:xs) = '[' : append (show x) (showItems show xs)
-- showItems :: (a -> String) -> [a] -> String
showItems show = ']' :
showItems show (x:xs) = ',' : append (show x) (showItems show xs)
-- fibs :: [Int]
fibs = 0 : 1 : zipWith add fibs (tail fibs)
-- main :: String
main = showList showInt (take 40 fibs)
Type checking is a crucial feature of Haskell. However, going from nothing to a type-checking Haskell compiler is very difficult. If you start by writing an interpreter for the above, adding type checking to it should be less daunting.
"Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this." This may not be true. See Naylor's article in haskell.org/wikiupload/0/0a/TMR-Issue10.pdf for more info on implementing a lazy interpreter in Haskell.
– Jared Updike
Mar 6 '14 at 18:30
add a comment |
If you're looking for a subset of Haskell that's easy to implement, you can do away with type classes and type checking. Without type classes, you don't need type inference to evaluate Haskell code.
I wrote a self-compiling Haskell subset compiler for a Code Golf challenge. It takes Haskell subset code on input and produces C code on output. I'm sorry there isn't a more readable version available; I lifted nested definitions by hand in the process of making it self-compiling.
For a student interested in implementing an interpreter for a subset of Haskell, I would recommend starting with the following features:
Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this.
Function definitions with pattern-matched arguments and guards. Only worry about variable, cons, nil, and
_
patterns.Simple expression syntax:
Integer literals
Character literals
(nil)
Function application (left associative)
Infix
:
(cons, right associative)Parenthesis
Variable names
Function names
More concretely, write an interpreter that can run this:
-- tail :: [a] -> [a]
tail (_:xs) = xs
-- append :: [a] -> [a] -> [a]
append ys = ys
append (x:xs) ys = x : append xs ys
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _ _ =
-- showList :: (a -> String) -> [a] -> String
showList _ = '[' : ']' :
showList show (x:xs) = '[' : append (show x) (showItems show xs)
-- showItems :: (a -> String) -> [a] -> String
showItems show = ']' :
showItems show (x:xs) = ',' : append (show x) (showItems show xs)
-- fibs :: [Int]
fibs = 0 : 1 : zipWith add fibs (tail fibs)
-- main :: String
main = showList showInt (take 40 fibs)
Type checking is a crucial feature of Haskell. However, going from nothing to a type-checking Haskell compiler is very difficult. If you start by writing an interpreter for the above, adding type checking to it should be less daunting.
If you're looking for a subset of Haskell that's easy to implement, you can do away with type classes and type checking. Without type classes, you don't need type inference to evaluate Haskell code.
I wrote a self-compiling Haskell subset compiler for a Code Golf challenge. It takes Haskell subset code on input and produces C code on output. I'm sorry there isn't a more readable version available; I lifted nested definitions by hand in the process of making it self-compiling.
For a student interested in implementing an interpreter for a subset of Haskell, I would recommend starting with the following features:
Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this.
Function definitions with pattern-matched arguments and guards. Only worry about variable, cons, nil, and
_
patterns.Simple expression syntax:
Integer literals
Character literals
(nil)
Function application (left associative)
Infix
:
(cons, right associative)Parenthesis
Variable names
Function names
More concretely, write an interpreter that can run this:
-- tail :: [a] -> [a]
tail (_:xs) = xs
-- append :: [a] -> [a] -> [a]
append ys = ys
append (x:xs) ys = x : append xs ys
-- zipWith :: (a -> b -> c) -> [a] -> [b] -> [c]
zipWith f (a:as) (b:bs) = f a b : zipWith f as bs
zipWith _ _ _ =
-- showList :: (a -> String) -> [a] -> String
showList _ = '[' : ']' :
showList show (x:xs) = '[' : append (show x) (showItems show xs)
-- showItems :: (a -> String) -> [a] -> String
showItems show = ']' :
showItems show (x:xs) = ',' : append (show x) (showItems show xs)
-- fibs :: [Int]
fibs = 0 : 1 : zipWith add fibs (tail fibs)
-- main :: String
main = showList showInt (take 40 fibs)
Type checking is a crucial feature of Haskell. However, going from nothing to a type-checking Haskell compiler is very difficult. If you start by writing an interpreter for the above, adding type checking to it should be less daunting.
edited Apr 13 '17 at 12:38
Community♦
11
11
answered Oct 11 '11 at 1:10
Joey Adams
28.1k1466101
28.1k1466101
"Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this." This may not be true. See Naylor's article in haskell.org/wikiupload/0/0a/TMR-Issue10.pdf for more info on implementing a lazy interpreter in Haskell.
– Jared Updike
Mar 6 '14 at 18:30
add a comment |
"Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this." This may not be true. See Naylor's article in haskell.org/wikiupload/0/0a/TMR-Issue10.pdf for more info on implementing a lazy interpreter in Haskell.
– Jared Updike
Mar 6 '14 at 18:30
"Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this." This may not be true. See Naylor's article in haskell.org/wikiupload/0/0a/TMR-Issue10.pdf for more info on implementing a lazy interpreter in Haskell.
– Jared Updike
Mar 6 '14 at 18:30
"Lazy evaluation. If the interpreter is in Haskell, you might not have to do anything for this." This may not be true. See Naylor's article in haskell.org/wikiupload/0/0a/TMR-Issue10.pdf for more info on implementing a lazy interpreter in Haskell.
– Jared Updike
Mar 6 '14 at 18:30
add a comment |
You might look at Happy (a yacc-like parser in Haskell) which has a Haskell parser.
add a comment |
You might look at Happy (a yacc-like parser in Haskell) which has a Haskell parser.
add a comment |
You might look at Happy (a yacc-like parser in Haskell) which has a Haskell parser.
You might look at Happy (a yacc-like parser in Haskell) which has a Haskell parser.
answered Sep 18 '09 at 17:30
Kathy Van Stone
19.4k22639
19.4k22639
add a comment |
add a comment |
This might be a good idea - make a tiny version of NetLogo in Haskell. Here is the tiny interpreter.
The links are dead. Any chance this content still exists somewhere else? I'd be curious...
– Nicolas Payette
Dec 9 '12 at 5:22
hmm it was a blog post and I have no idea what keywords to use to search for it. A good lesson to include more substantial info when providing a link...
– Claudiu
Dec 9 '12 at 23:22
1
A Google search for "netlogo haskell" turns up... this question. Anyway, no big deal. Thanks!
– Nicolas Payette
Dec 10 '12 at 18:40
add a comment |
This might be a good idea - make a tiny version of NetLogo in Haskell. Here is the tiny interpreter.
The links are dead. Any chance this content still exists somewhere else? I'd be curious...
– Nicolas Payette
Dec 9 '12 at 5:22
hmm it was a blog post and I have no idea what keywords to use to search for it. A good lesson to include more substantial info when providing a link...
– Claudiu
Dec 9 '12 at 23:22
1
A Google search for "netlogo haskell" turns up... this question. Anyway, no big deal. Thanks!
– Nicolas Payette
Dec 10 '12 at 18:40
add a comment |
This might be a good idea - make a tiny version of NetLogo in Haskell. Here is the tiny interpreter.
This might be a good idea - make a tiny version of NetLogo in Haskell. Here is the tiny interpreter.
answered Sep 28 '09 at 22:55
Claudiu
125k120392576
125k120392576
The links are dead. Any chance this content still exists somewhere else? I'd be curious...
– Nicolas Payette
Dec 9 '12 at 5:22
hmm it was a blog post and I have no idea what keywords to use to search for it. A good lesson to include more substantial info when providing a link...
– Claudiu
Dec 9 '12 at 23:22
1
A Google search for "netlogo haskell" turns up... this question. Anyway, no big deal. Thanks!
– Nicolas Payette
Dec 10 '12 at 18:40
add a comment |
The links are dead. Any chance this content still exists somewhere else? I'd be curious...
– Nicolas Payette
Dec 9 '12 at 5:22
hmm it was a blog post and I have no idea what keywords to use to search for it. A good lesson to include more substantial info when providing a link...
– Claudiu
Dec 9 '12 at 23:22
1
A Google search for "netlogo haskell" turns up... this question. Anyway, no big deal. Thanks!
– Nicolas Payette
Dec 10 '12 at 18:40
The links are dead. Any chance this content still exists somewhere else? I'd be curious...
– Nicolas Payette
Dec 9 '12 at 5:22
The links are dead. Any chance this content still exists somewhere else? I'd be curious...
– Nicolas Payette
Dec 9 '12 at 5:22
hmm it was a blog post and I have no idea what keywords to use to search for it. A good lesson to include more substantial info when providing a link...
– Claudiu
Dec 9 '12 at 23:22
hmm it was a blog post and I have no idea what keywords to use to search for it. A good lesson to include more substantial info when providing a link...
– Claudiu
Dec 9 '12 at 23:22
1
1
A Google search for "netlogo haskell" turns up... this question. Anyway, no big deal. Thanks!
– Nicolas Payette
Dec 10 '12 at 18:40
A Google search for "netlogo haskell" turns up... this question. Anyway, no big deal. Thanks!
– Nicolas Payette
Dec 10 '12 at 18:40
add a comment |
see if helium would make a better base to build upon than standard haskell.
add a comment |
see if helium would make a better base to build upon than standard haskell.
add a comment |
see if helium would make a better base to build upon than standard haskell.
see if helium would make a better base to build upon than standard haskell.
answered Sep 18 '09 at 21:35
Martin DeMello
7,18153763
7,18153763
add a comment |
add a comment |
Uhc/Ehc is a series of compilers enabling/disabling various Haskell features.
http://www.cs.uu.nl/wiki/Ehc/WebHome#What_is_UHC_And_EHC
add a comment |
Uhc/Ehc is a series of compilers enabling/disabling various Haskell features.
http://www.cs.uu.nl/wiki/Ehc/WebHome#What_is_UHC_And_EHC
add a comment |
Uhc/Ehc is a series of compilers enabling/disabling various Haskell features.
http://www.cs.uu.nl/wiki/Ehc/WebHome#What_is_UHC_And_EHC
Uhc/Ehc is a series of compilers enabling/disabling various Haskell features.
http://www.cs.uu.nl/wiki/Ehc/WebHome#What_is_UHC_And_EHC
answered Sep 21 '09 at 22:20
ja.
4,0271521
4,0271521
add a comment |
add a comment |
I've been told that Idris has a fairly compact parser, not sure if it's really suitable for alteration, but it's written in Haskell.
add a comment |
I've been told that Idris has a fairly compact parser, not sure if it's really suitable for alteration, but it's written in Haskell.
add a comment |
I've been told that Idris has a fairly compact parser, not sure if it's really suitable for alteration, but it's written in Haskell.
I've been told that Idris has a fairly compact parser, not sure if it's really suitable for alteration, but it's written in Haskell.
answered Apr 7 '12 at 22:03
Jeff Burdges
2,5461536
2,5461536
add a comment |
add a comment |
Andrej Bauer's Programming Language Zoo has a small implementation of a purely functional programming language somewhat cheekily named "minihaskell". It is about 700 lines of OCaml, so very easy to digest.
The site also contains toy versions of ML-style, Prolog-style and OO programming languages.
add a comment |
Andrej Bauer's Programming Language Zoo has a small implementation of a purely functional programming language somewhat cheekily named "minihaskell". It is about 700 lines of OCaml, so very easy to digest.
The site also contains toy versions of ML-style, Prolog-style and OO programming languages.
add a comment |
Andrej Bauer's Programming Language Zoo has a small implementation of a purely functional programming language somewhat cheekily named "minihaskell". It is about 700 lines of OCaml, so very easy to digest.
The site also contains toy versions of ML-style, Prolog-style and OO programming languages.
Andrej Bauer's Programming Language Zoo has a small implementation of a purely functional programming language somewhat cheekily named "minihaskell". It is about 700 lines of OCaml, so very easy to digest.
The site also contains toy versions of ML-style, Prolog-style and OO programming languages.
answered May 12 '12 at 10:25
niklas
311
311
add a comment |
add a comment |
Don't you think it would be easier to take the GHC sources and strip out what you don't want, than it would be to write your own Haskell interpreter from scratch? Generally speaking, there should be a lot less effort involved in removing features as opposed to creating/adding features.
GHC is written in Haskell anyway, so technically that stays with your question of a Haskell interpreter written in Haskell.
It probably wouldn't be too hard to make the whole thing statically linked and then only distribute your customized GHCi, so that the students can't load other Haskell source modules. As to how much work it would take to prevent them from loading other Haskell object files, I have no idea. You might want to disable FFI too, if you have a bunch of cheaters in your classes :)
1
This is not as easy as it sounds, as many features depend on others. But perhaps the OP just wants to not import Prelude and instead provide his own. Most of Haskell that you see are normal functions, not specific features of the runtime. (But of course, a lot are.)
– jrockway
Sep 23 '09 at 7:44
add a comment |
Don't you think it would be easier to take the GHC sources and strip out what you don't want, than it would be to write your own Haskell interpreter from scratch? Generally speaking, there should be a lot less effort involved in removing features as opposed to creating/adding features.
GHC is written in Haskell anyway, so technically that stays with your question of a Haskell interpreter written in Haskell.
It probably wouldn't be too hard to make the whole thing statically linked and then only distribute your customized GHCi, so that the students can't load other Haskell source modules. As to how much work it would take to prevent them from loading other Haskell object files, I have no idea. You might want to disable FFI too, if you have a bunch of cheaters in your classes :)
1
This is not as easy as it sounds, as many features depend on others. But perhaps the OP just wants to not import Prelude and instead provide his own. Most of Haskell that you see are normal functions, not specific features of the runtime. (But of course, a lot are.)
– jrockway
Sep 23 '09 at 7:44
add a comment |
Don't you think it would be easier to take the GHC sources and strip out what you don't want, than it would be to write your own Haskell interpreter from scratch? Generally speaking, there should be a lot less effort involved in removing features as opposed to creating/adding features.
GHC is written in Haskell anyway, so technically that stays with your question of a Haskell interpreter written in Haskell.
It probably wouldn't be too hard to make the whole thing statically linked and then only distribute your customized GHCi, so that the students can't load other Haskell source modules. As to how much work it would take to prevent them from loading other Haskell object files, I have no idea. You might want to disable FFI too, if you have a bunch of cheaters in your classes :)
Don't you think it would be easier to take the GHC sources and strip out what you don't want, than it would be to write your own Haskell interpreter from scratch? Generally speaking, there should be a lot less effort involved in removing features as opposed to creating/adding features.
GHC is written in Haskell anyway, so technically that stays with your question of a Haskell interpreter written in Haskell.
It probably wouldn't be too hard to make the whole thing statically linked and then only distribute your customized GHCi, so that the students can't load other Haskell source modules. As to how much work it would take to prevent them from loading other Haskell object files, I have no idea. You might want to disable FFI too, if you have a bunch of cheaters in your classes :)
answered Sep 18 '09 at 22:03
Mark Rushakoff
180k29359370
180k29359370
1
This is not as easy as it sounds, as many features depend on others. But perhaps the OP just wants to not import Prelude and instead provide his own. Most of Haskell that you see are normal functions, not specific features of the runtime. (But of course, a lot are.)
– jrockway
Sep 23 '09 at 7:44
add a comment |
1
This is not as easy as it sounds, as many features depend on others. But perhaps the OP just wants to not import Prelude and instead provide his own. Most of Haskell that you see are normal functions, not specific features of the runtime. (But of course, a lot are.)
– jrockway
Sep 23 '09 at 7:44
1
1
This is not as easy as it sounds, as many features depend on others. But perhaps the OP just wants to not import Prelude and instead provide his own. Most of Haskell that you see are normal functions, not specific features of the runtime. (But of course, a lot are.)
– jrockway
Sep 23 '09 at 7:44
This is not as easy as it sounds, as many features depend on others. But perhaps the OP just wants to not import Prelude and instead provide his own. Most of Haskell that you see are normal functions, not specific features of the runtime. (But of course, a lot are.)
– jrockway
Sep 23 '09 at 7:44
add a comment |
The reason why there are so many LISP interpreters is that LISP is basically a predecessor of JSON: a simple format to encode data. This makes the frontend part quite easy to handle. Compared to that, Haskell, especially with Language Extensions, is not the easiest language to parse.
These are some syntactical constructs that sound tricky to get right:
- operators with configurable precedence, associativity, and fixity,
- nested comments
- layout rule
- pattern syntax
do
- blocks and desugaring to monadic code
Each of these, except maybe the operators, could be tackled by students after their Compiler Construction Course, but it would take the focus away from how Haskell actually works. In addition to that, you might not want to implement all syntactical constructs of Haskell directly, but instead implement passes to get rid of them. Which brings us to the literal core of the issue, pun fully intended.
My suggestion is to implement typechecking and an interpreter for Core
instead of full Haskell. Both of these tasks are quite intricate by themselves already.
This language, while still a strongly typed functional language, is way less complicated to deal with in terms of optimization and code generation.
However, it is still independent from the underlying machine.
Therefore, GHC uses it as an intermediary language and translates most syntaxical constructs of Haskell into it.
Additionally, you should not shy away from using GHC's (or another compiler's) frontend.
I'd not consider that as cheating since custom LISPs use the host LISP system's parser (at least during bootstrapping). Cleaning up Core
snippets and presenting them to students, along with the original code, should allow you to give an overview of what the frontend does, and why it is preferable to not reimplement it.
Here are a few links to the documentation of Core
as used in GHC:
- System FC: equality constraints and coercions
- GHC/As a library
- The
Core
type
add a comment |
The reason why there are so many LISP interpreters is that LISP is basically a predecessor of JSON: a simple format to encode data. This makes the frontend part quite easy to handle. Compared to that, Haskell, especially with Language Extensions, is not the easiest language to parse.
These are some syntactical constructs that sound tricky to get right:
- operators with configurable precedence, associativity, and fixity,
- nested comments
- layout rule
- pattern syntax
do
- blocks and desugaring to monadic code
Each of these, except maybe the operators, could be tackled by students after their Compiler Construction Course, but it would take the focus away from how Haskell actually works. In addition to that, you might not want to implement all syntactical constructs of Haskell directly, but instead implement passes to get rid of them. Which brings us to the literal core of the issue, pun fully intended.
My suggestion is to implement typechecking and an interpreter for Core
instead of full Haskell. Both of these tasks are quite intricate by themselves already.
This language, while still a strongly typed functional language, is way less complicated to deal with in terms of optimization and code generation.
However, it is still independent from the underlying machine.
Therefore, GHC uses it as an intermediary language and translates most syntaxical constructs of Haskell into it.
Additionally, you should not shy away from using GHC's (or another compiler's) frontend.
I'd not consider that as cheating since custom LISPs use the host LISP system's parser (at least during bootstrapping). Cleaning up Core
snippets and presenting them to students, along with the original code, should allow you to give an overview of what the frontend does, and why it is preferable to not reimplement it.
Here are a few links to the documentation of Core
as used in GHC:
- System FC: equality constraints and coercions
- GHC/As a library
- The
Core
type
add a comment |
The reason why there are so many LISP interpreters is that LISP is basically a predecessor of JSON: a simple format to encode data. This makes the frontend part quite easy to handle. Compared to that, Haskell, especially with Language Extensions, is not the easiest language to parse.
These are some syntactical constructs that sound tricky to get right:
- operators with configurable precedence, associativity, and fixity,
- nested comments
- layout rule
- pattern syntax
do
- blocks and desugaring to monadic code
Each of these, except maybe the operators, could be tackled by students after their Compiler Construction Course, but it would take the focus away from how Haskell actually works. In addition to that, you might not want to implement all syntactical constructs of Haskell directly, but instead implement passes to get rid of them. Which brings us to the literal core of the issue, pun fully intended.
My suggestion is to implement typechecking and an interpreter for Core
instead of full Haskell. Both of these tasks are quite intricate by themselves already.
This language, while still a strongly typed functional language, is way less complicated to deal with in terms of optimization and code generation.
However, it is still independent from the underlying machine.
Therefore, GHC uses it as an intermediary language and translates most syntaxical constructs of Haskell into it.
Additionally, you should not shy away from using GHC's (or another compiler's) frontend.
I'd not consider that as cheating since custom LISPs use the host LISP system's parser (at least during bootstrapping). Cleaning up Core
snippets and presenting them to students, along with the original code, should allow you to give an overview of what the frontend does, and why it is preferable to not reimplement it.
Here are a few links to the documentation of Core
as used in GHC:
- System FC: equality constraints and coercions
- GHC/As a library
- The
Core
type
The reason why there are so many LISP interpreters is that LISP is basically a predecessor of JSON: a simple format to encode data. This makes the frontend part quite easy to handle. Compared to that, Haskell, especially with Language Extensions, is not the easiest language to parse.
These are some syntactical constructs that sound tricky to get right:
- operators with configurable precedence, associativity, and fixity,
- nested comments
- layout rule
- pattern syntax
do
- blocks and desugaring to monadic code
Each of these, except maybe the operators, could be tackled by students after their Compiler Construction Course, but it would take the focus away from how Haskell actually works. In addition to that, you might not want to implement all syntactical constructs of Haskell directly, but instead implement passes to get rid of them. Which brings us to the literal core of the issue, pun fully intended.
My suggestion is to implement typechecking and an interpreter for Core
instead of full Haskell. Both of these tasks are quite intricate by themselves already.
This language, while still a strongly typed functional language, is way less complicated to deal with in terms of optimization and code generation.
However, it is still independent from the underlying machine.
Therefore, GHC uses it as an intermediary language and translates most syntaxical constructs of Haskell into it.
Additionally, you should not shy away from using GHC's (or another compiler's) frontend.
I'd not consider that as cheating since custom LISPs use the host LISP system's parser (at least during bootstrapping). Cleaning up Core
snippets and presenting them to students, along with the original code, should allow you to give an overview of what the frontend does, and why it is preferable to not reimplement it.
Here are a few links to the documentation of Core
as used in GHC:
- System FC: equality constraints and coercions
- GHC/As a library
- The
Core
type
answered Jun 14 at 12:55
MauganRa
43058
43058
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f1445827%2fwrite-a-haskell-interpreter-in-haskell%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
I have a WIP Haskell dialect implemented with Typing Haskell in Haskell as a base. There's a demo of it here chrisdone.com/toys/duet-delta It's not ready for public open source release, but I could share the source with you if interested.
– Christopher Done
Aug 10 '17 at 11:33