{"id":13723363,"url":"https://github.com/tonymorris/fp-course","last_synced_at":"2025-05-16T07:03:45.317Z","repository":{"id":1562455,"uuid":"1977846","full_name":"tonymorris/fp-course","owner":"tonymorris","description":"Functional Programming Course","archived":false,"fork":false,"pushed_at":"2023-03-06T02:28:36.000Z","size":3501,"stargazers_count":1030,"open_issues_count":18,"forks_count":133,"subscribers_count":50,"default_branch":"master","last_synced_at":"2025-04-08T16:07:35.313Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":"","language":"Haskell","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/tonymorris.png","metadata":{"files":{"readme":"README.markdown","changelog":"changelog","contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2011-06-30T12:40:12.000Z","updated_at":"2025-03-29T15:51:56.000Z","dependencies_parsed_at":"2023-07-05T17:15:31.754Z","dependency_job_id":null,"html_url":"https://github.com/tonymorris/fp-course","commit_stats":{"total_commits":636,"total_committers":48,"mean_commits":13.25,"dds":0.1588050314465409,"last_synced_commit":"b305640b7ef8fbaf99e0cf9cb3743b107fc7ec84"},"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tonymorris%2Ffp-course","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tonymorris%2Ffp-course/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tonymorris%2Ffp-course/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/tonymorris%2Ffp-course/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/tonymorris","download_url":"https://codeload.github.com/tonymorris/fp-course/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254485052,"owners_count":22078767,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2024-08-03T01:01:40.060Z","updated_at":"2025-05-16T07:03:45.299Z","avatar_url":"https://github.com/tonymorris.png","language":"Haskell","funding_links":[],"categories":["Languages"],"sub_categories":["Other Languages"],"readme":"# Functional Programming Course\n\n![Data61](http://i.imgur.com/0h9dFhl.png)\n\n### Written by Tony Morris \u0026 Mark Hibberd for Data61 (formerly NICTA)\n\n### With contributions from individuals (thanks!)\n\n#### Special note 1\n\nIf you have arrived here by https://github.com/data61/fp-course and you are\nlooking for the *answers* (not the exercises), please go to https://github.com/tonymorris/fp-course\n\n#### Special note 2\n\nAs of February 2017, this repository is taking the place of the repository hosted at\nhttps://github.com/NICTA/course which is deprecated.\n\nData61 replaces what was NICTA since July 2016. The new repository is located at\nhttps://github.com/data61/fp-course.\n\n#### Introduction\n\nThe course is structured according to a linear progression and uses the Haskell\nprogramming language to learn programming concepts pertaining to functional\nprogramming.\n\nExercises are annotated with a comment containing the word \"Exercise.\" The existing code compiles, however answers have\nbeen replaced with a call to the Haskell `error` function and so the code will throw an exception if it is run. Some\nexercises contain tips, which are annotated with a preceding \"Tip:\". It is not necessary to adhere to tips. Tips are\nprovided for potential guidance, which may be discarded if you prefer a different path to a solution.\n\nThe exercises are designed in a way that requires personal guidance, so if you\nattempt it on your own and feel a little lost, this is normal. All the\ninstructions are not contained herein.\n\n### Getting Help\n\nThere are two mailing lists for asking questions. All questions are welcome,\nhowever, your first post might be moderated. This is simply to prevent spam.\n\n1. [[nicta-fp]](https://groups.google.com/forum/#!forum/nicta-fp) is a Google\n   Group for any queries related to functional programming. This mailing list is\n   owned by Data61 and is open to the public. Questions relating to this course\n   are most welcome here.\n\n2. [[haskell-exercises]](https://groups.google.com/forum/#!forum/haskell-exercises)\n   is a Google Group for queries related specifically to this Data61 functional\n   programming course material. This mailing list is not owned by Data61, but is\n   run by others who are keen to share ideas relating to the course.\n\n3. \\#nicta-course [on Freenode](irc://irc.freenode.net/#nicta-course) is an IRC channel that\n   is operated by others who are going through this course material on their\n   own time and effort.\n\n4. \\#qfpl [on Freenode](irc://irc.freenode.net/#qfpl) is the IRC channel of the\n   Queensland Functional Programming Lab - the team that runs the course in Brisbane.\n\n5. \\#scalaz [on Freenode](irc://irc.freenode.net/#scalaz) is an IRC channel that is operated\n   by others who are keen to share ideas relating to functional programming in\n   general. Most of the participants of this channel have completed the Data61\n   functional programming course to some extent. They are in various timezones\n   and share a passion for functional programming, so may be able to provide\n   relatively quick assistance with questions.\n\n### Getting Started\n\n**NOTE** If you do not wish to install these dependencies, you may use a virtual machine\ninstead. [Instructions](ops/README.md) for automatically building a virtual machine are\navailable in this repository for your convenience.\n\n1. Install the Glasgow Haskell Compiler (GHC) version 7.10 or higher.\n\n2. Change to the directory containing this document.\n\n3. Execute the command `ghci`, which will compile and load all the source code.\n   You may need to set permissions on the root directory and the ghci configuration\n   file, `chmod go-w .ghci ./`.\n\n4. Inspect the introductory modules to get a feel for Haskell's syntax, then move\n   on to the exercises starting with `Course.Optional`. The\n   [Progression](#progression) section of this document lists the recommended\n   order in which to attempt the exercises.\n\n5. Edit a source file to a proposed solution to an exercise. At the `ghci`\n   prompt, issue the command `:reload`. This will compile your solution and\n   reload it in the GHC interpreter. You may use `:r` for short.\n\n### Tips after having started\n\n1. Some questions take a particular form. These are called *WTF questions*. WTF\n   questions are those of this form or similar:\n  * What does ____ mean?\n  * What does the ____ function mean?\n  * What is a ____ ?\n  * Where did ____ come from ?\n  * What is the structure of ____ ?\n\n  They are all answerable with the `:info` command. For example, suppose you\n  have the question, \"What does the `swiggletwoop` function mean?\" You may\n  answer this at GHCi with:\n\n  `\u003e :info swiggletwoop`\n\n  You may also use `:i` for short.\n\n2. Functional Programming techniques rely heavily on types. This reliance may\n   feel foreign at first, however, it is an important part of this course. If\n   you wish to know the type of an expression or value, use `:type`. For\n   example,\n\n   `\u003e :type reverse`\n\n   `List t -\u003e List t`\n\n   This tells you that the `reverse` function takes a list of elements of some\n   arbitrary type (`t`) and returns a list of elements of that same type. Try\n   it.\n\n   You may also use `:t` for short.\n\n3. GHCi has TAB-completion. For example you might type the following:\n\n   `\u003e :type rev`\n\n   Now hit the TAB key. If there is only one function in scope that begins with\n   the characters `rev`, then that name will auto-complete. Try it. This\n   completion is context-sensitive. For example, it doesn't make sense to ask\n   for the type of a data type itself, so data type names will not auto-complete\n   in that context, however, if you ask for `:info`, then they are included in\n   that context. Be aware of this when you use auto-complete.\n\n   This also works for file names:\n\n   `\u003e readFile \"/etc/pas\"`\n\n   Now hit the TAB key. If there is only one existing filename on a path that\n   begins with `/etc/pas`, then that name will auto-complete. Try it.\n\n   If there is more than one identifier that can complete, hit TAB twice\n   quickly. This will present you with your options to complete.\n\n4. Follow the types.\n\n   You may find yourself in a position of being unsure how to proceed for a\n   given exercise. You are encouraged to adopt a different perspective. Instead\n   of asking how to proceed, ask how you might proceed while adhering to the\n   guideline provided by the types for the exercise at hand.\n\n   It is possible to follow the types without achieving the desired goal,\n   however, this is reasonably unlikely at the start. As you become more reliant\n   on following the types, you will develop more trust in the potential paths\n   that they can take you, including identification of false paths.\n\n   Your instructor must guide you where types fall short, but you should also\n   take the first step. Do it.\n\n5. Do not use tab characters\n\n   Set up your text editor to use space characters rather than tabs.\n   Using tab characters in Haskell can lead to confusing error messages.\n   GHC will give you a warning if your program contains a tab character.\n\n6. Do not use the stack build tool. It does not work.\n\n### Running the tests\n\nTests are available as a [tasty](https://hackage.haskell.org/package/tasty)\ntest suite.\n\n#### tasty\n\nTasty tests are stored under the `test/` directory. Each module from the course\nthat has tests has a corresponding `\u003cMODULE\u003eTest.hs` file. Within each test\nmodule, tests for each function are grouped using the `testGroup` function.\nWithin each test group there are test cases (`testCase` function), and\nproperties (`testProperty` function).\n\nBefore running the tests, ensure that you have an up-to-date installation\nof GHC and cabal-install from your system package manager or use the minimal\ninstallers found at [haskell.org](https://www.haskell.org/downloads#minimal).\n\nTo run the full test suite, build the project as follows:\n\n    \u003e cabal update\n    \u003e cabal install --only-dependencies --enable-tests\n    \u003e cabal configure --enable-tests\n    \u003e cabal build\n    \u003e cabal test\n\nTasty will also allow you to run only those tests whose description match a\npattern. Tests are organised in nested groups named after the relevant module\nand function, so pattern matching should be intuitive. For example, to run the\ntests for the `List` module you could run:\n\n    \u003e cabal test tasty --show-detail=direct --test-option=--pattern=\"Tests.List.\"\n\nLikewise, to run only the tests for the `headOr` function in the `List` module, you could use:\n\n    \u003e cabal test tasty --show-detail=direct --test-option=--pattern=\"List.headOr\"\n\nIn addition, GHCi may be used to run tasty tests. Assuming you have run `ghci`\nfrom the root of the project, you may do the following. Remember that GHCi has\ntab completion, so you can save yourself some typing.\n\n    \u003e -- import the defaultMain function from Tasty - runs something of type TestTree\n    \u003e import Test.Tasty (defaultMain)\n    \u003e\n    \u003e -- Load the test module you'd like to run tests for\n    \u003e :l test/Course/ListTest.hs\n    \u003e\n    \u003e -- Browse the contents of the loaded module - anything of type TestTree\n    \u003e -- may be run\n    \u003e :browse Course.ListTest\n    \u003e\n    \u003e -- Run test for a particular function\n    \u003e defaultMain headOrTest\n\n\n#### doctest\n\nThe doctest tests are a mirror of the tasty tests that reside in comments\nalongside the code. They are not executable, but examples can be copied into\nGHCI. Examples begin with `\u003e\u003e\u003e` while properties begin with `prop\u003e`.\n\n### Progression\n\nIt is recommended to perform some exercises before others. The first step is to\ninspect the introduction modules.\n\n* `Course.ExactlyOne`\n* `Course.Validation`\n\nThey contain examples of data structures and Haskell syntax. They do not contain\nexercises and exist to provide a cursory examination of Haskell syntax. The next\nstep is to complete the exercises in `Course.Optional`.\n\nAfter this, the following progression of modules is recommended:\n\n* `Course.List`\n* `Course.Functor`\n* `Course.Applicative`\n* `Course.Monad`\n* `Course.FileIO`\n* `Course.State`\n* `Course.StateT`\n* `Course.Extend`\n* `Course.Comonad`\n* `Course.Compose`\n* `Course.Traversable`\n* `Course.ListZipper`\n* `Course.Parser` *(see also `Course.Person` for the parsing rules)*\n* `Course.MoreParser`\n* `Course.JsonParser`\n* `Course.Interactive`\n* `Course.Anagrams`\n* `Course.FastAnagrams`\n* `Course.Cheque`\n\nDuring this progression, it is often the case that some exercises are abandoned\ndue to time constraints and the benefit of completing some exercises over\nothers. For example, in the progression, `Course.Functor` to `Course.Monad`, the\nexercises repeat a similar theme. Instead, a participant may wish to do\ndifferent exercises, such as `Course.Parser`. In this case, the remaining\nanswers are filled out, so that progress on to `Course.Parser` can begin\n(which depends on correct answers up to `Course.Monad`). It is recommended to\ntake this deviation if it is felt that there is more reward in doing so.\n\nAnswers for the exercises can be found here:\n[https://github.com/tonymorris/fp-course](https://github.com/tonymorris/fp-course)\n\nAfter these are completed, complete the exercises in the `projects` directory.\n\n### Leksah\n\nIf you choose to use the [Leksah IDE for Haskell](http://leksah.org/), the\nfollowing tips are recommended:\n\n* [Install Leksah from github](https://github.com/leksah/leksah#getting-leksah).\n  If you are using Nix to install Leksah launch it with `./leksah-nix.sh ghc822`\n  as the Nix files for this course use GHC 8.2.2.\n* Clone this fp-course git repo use File -\u003e Open Project to open the cabal.project file.\n* Mouse over the toolbar items near the middle of toolbar to see the names of them.\n  Set the following items on/off:\n  * `Build in the background and report errors` ON - unless you prefer to triger builds\n     manualy with Ctrl + B to build (Command + B on OS X)\n  * `Use GHC to compile` ON\n  * `Use GHCJS to compile` OFF\n  * `Use GHCi debugger to build and run` ON\n  * `Make documentation while building` OFF\n  * `Run unit tests when building` ON\n  * `Run benchmakrs when building` OFF\n  * `Make dependent packages` ON\n* If you are using Nix, click on the nix button on the toolbar (tool tip is \"Refresh\n  Leksah's cached nix environment variables for the active project\").  This will use\n  `nix-shell` to build an environment for running the builds in.  If `nix-shell` has\n  not been run before for the `fp-course` repo it may take some time to complete.\n  When it is finished a line of green '-' characters should be printed in the Panes -\u003e Log.\n* Restart Leksah as there is a bug in the metadata collection that\n  will prevent it from indexing the new project without a restart.\n* Ctrl + B to build (Command + B on OS X).\n* The test failures should show up in Panes -\u003e Errors.\n* Pane -\u003e Log often has useful error messages.\n* Ctrl + J (Command + J on OS X) selects the next item in\n  Errors pane and goes to it in the source (hold down Shift\n  to go to previous item).\n* Ctrl + Enter on a line starting \"-- \u003e\u003e\u003e\" will run the\n  selected expression in GHCi (Ctrl + Enter on OS X too).\n  The output goes to Panes -\u003e Log (on Linux it will also show up in Panes -\u003e Output).\n* The last GHCi expression is reevaluated after each :reload\n  triggered by changes in the code.\n\n### Introducing Haskell\n\nThis section is a guide for the instructor to introduce Haskell syntax. Each of\nthese points should be covered before attempting the exercises.\n\n* values, assignment\n* type signatures `::` reads as *has the type*\n  * The `-\u003e` in a type signature is *right-associative*\n* functions are values\n* functions take arguments\n  * functions take *only one argument* but we approximate without spoken\n    language\n  * functions can be declared inline using *lambda expressions*\n  * the `\\` symbol in a lambda expression denotes a Greek lambda\n* operators, beginning with non-alpha character, are in infix position by\n  default\n  * use in prefix position by surrounding with *(parentheses)*\n* regular identifiers, beginning with alpha character, are in prefix position by\n  default\n  * use in infix position by surrounding with ``backticks``\n* polymorphism\n  * type variables *always* start with a lower-case character\n* data types, declared using the `data` keyword\n  * following the `data` keyword is the *data type name*\n  * following the data type name are zero of more type variables\n  * then `=` sign\n  * data types have zero or more constructors\n    * data type constructors start with an upper-case character, or colon `(:)`\n  * following each constructor is a list of zero or more *constructor arguments*\n  * between each constructor is a pipe symbol `(|)`\n  * the `deriving` keyword gives us default implementations for some functions\n    on that data type\n  * when constructors appear on the left side of `=` we are *pattern-matching*\n  * when constructors appear on the right side of `=` we are *constructing*\n* type-classes\n\n### Learning the tools\n\nWhen this course is run in-person, some tools, particularly within Haskell, are\ncovered first.\n\n* GHCi\n  * `:type`\n  * `:info`\n* values\n* type signatures\n  * `x :: T` is read as *x is of the type T*\n* functions are values\n* functions take arguments\n* functions take one argument\n* lambda expressions\n* operators (infix/prefix)\n  * identifiers starting with `isAlpha` are prefix by default, infix surrounded in backticks (\\`)\n  * other identifiers are infix by default, prefix surrounded in parentheses\n* data types\n  * `data` keyword\n  * recursive data types\n* pattern matching\n* `deriving` keyword\n* type-classes\n* type parameters\n  * always lower-case 'a'..'z'\n  * aka generics, templates C++, parametric polymorphism\n* running the tests\n  * `cabal test`\n\n### Parser grammar assistance\n\nThe exercises in `Parser.hs` can be assisted by stating problems in a specific way, with a conversion to code.\n\n| English   | Parser library                    |\n|-----------|-----------------------------------|\n| and then  | `bindParser` `\u003e\u003e=`                |\n| always    | `valueParser` `pure`              |\n| or        | `\\|\\|\\|`                             |\n| 0 or many | `list`                            |\n| 1 or many | `list1`                           |\n| is        | `is`                              |\n| exactly n | `thisMany n`                      |\n| fail      | `failed`                          |\n| call it x | `\\x -\u003e`                           |\n\n### Monad comprehension\n\n##### do-notation\n\n* insert the word `do`\n* turn `\u003e\u003e=` into `\u003c-`\n* delete `-\u003e`\n* delete `\\`\n* swap each side of `\u003c-`\n\n##### LINQ\n\n* write `from` on each line\n* turn `\u003e\u003e=` into in\n* delete `-\u003e`\n* delete `\\`\n* swap each side of `in`\n* turn value into `select`\n\n### Demonstrate IO maintains referential transparency\n\nAre these two programs, the same program?\n\n    p1 ::\n      IO ()\n    p1 =\n      let file = \"/tmp/file\"\n      in  do  _ \u003c- writeFile file \"abcdef\"\n              x \u003c- readFile file\n              _ \u003c- putStrLn x\n              _ \u003c- writeFile file \"ghijkl\"\n              y \u003c- readFile file\n              putStrLn (show (x, y))\n\n    p2 ::\n      IO ()\n    p2 =\n      let file = \"/tmp/file\"\n          expr = readFile file\n      in  do  _ \u003c- writeFile file \"abcdef\"\n              x \u003c- expr\n              _ \u003c- putStrLn x\n              _ \u003c- writeFile file \"ghijkl\"\n              y \u003c- expr\n              putStrLn (show (x, y))\n\nWhat about these two programs?\n\n    def writeFile(filename, contents):\n        with open(filename, \"w\") as f:\n            f.write(contents)\n\n    def readFile(filename):\n        contents = \"\"\n        with open(filename, \"r\") as f:\n            contents = f.read()\n            return contents\n\n    def p1():\n        file = \"/tmp/file\"\n\n        writeFile(file, \"abcdef\")\n        x = readFile(file)\n        print(x)\n        writeFile(file, \"ghijkl\")\n        y = readFile(file)\n        print (x + y)\n\n    def p2():\n        file = \"/tmp/file\"\n        expr = readFile(file)\n\n        writeFile(file, \"abcdef\")\n        x = expr\n        print(x)\n        writeFile(file, \"ghijkl\")\n        y = expr\n        print (x + y)\n\n### One-day\n\nSometimes this course material is condensed into one-day. In these cases, the\nfollowing exercises are recommended:\n\n* `Optional`\n  * `mapOptional`\n  * `bindOptional`\n  * `(??)`\n  * `(\u003c+\u003e)`\n* `List`\n  * `headOr`\n  * `product`\n  * `length`\n  * `map`\n  * `filter`\n  * `(++)`\n  * `flatMap`\n  * `reverse`\n* `Functor`\n  * `instance Functor List`\n  * `instance Functor Optional`\n  * `instance Functor ((-\u003e) t)`\n  * `instance Functor void`\n* `Applicative`\n  * `instance Applicative List`\n  * `instance Applicative Optional`\n  * `instance Applicative ((-\u003e) t)`\n  * `lift2`\n  * `sequence`\n* `FileIO`\n\n### References\n\n* [The Haskell `error` function](http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#v:error)\n\n* [Glasgow Haskell Compiler](http://haskell.org/ghc)\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftonymorris%2Ffp-course","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ftonymorris%2Ffp-course","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ftonymorris%2Ffp-course/lists"}