CSCI0200
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Write
        • Owners
        • Signed-in users
        • Everyone
        Owners Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Note Insights Sharing URL Help
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Write
Owners
  • Owners
  • Signed-in users
  • Everyone
Owners Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    --- tags: resources, spr22 --- # Pyret Crash Course for Java Programmers This guide summarizes the essential notations that you'll need for the Pyret segment of the class. Keep in mind that Pyret is a full-fledged language and CSCI0200 will use only a small (yet powerful) portion of it. **With the exception of looking in the documentation for the names of build-in functions on lists (and maybe strings), everything you need to know about Pyret will be covered in lecture.** If you are searching the documentation for some new construct or way to do things, you're almost certainly off-track! The point isn't for you to learn how to write the constructs you already know (like for-loops) in Pyret. The point is to get you to write similar programs to what you've written before with a different set of constructs. Lecture will cover those constructs. [TOC] ## Programs In Java, you are used to thinking of everything in terms of classes. In functional programming, we often work with primitive data (numbers, strings, booleans) or with lists of primitive data. None of these need a notion of classes. The simplest functional program is a single number, like ```=pyret 3 ``` Yes, this is a complete program. Go to Pyret, type this at the prompt, and you get the value of this expression (which is, not surprisingly, 3). ## Functions Here is a function definition. `Number` is the type for all numbers (there is no distinction between integer, double, float, etc). `doc` is the documentation string. Functions live in your file, they don't have to be put inside anything (like a class). ```=pyret fun square(n :: Number) -> Number: doc: "compute the square of a number" n * n end ``` Note that there is no `return` annotation. In functional programming, function bodies consist of single expressions, or perhaps some statements naming intermediate values followed by the expression to compute. The result of that expression is the result of the function. Here's an example with intermediate value names. ```=pyret fun big-square(n :: Number) -> Boolean: doc: "determine whether square of a number is above 100" sqr = n * n sqr > 100 # the result of this line gets returned end ``` When you want to use a function, just call it with arguments, as you are used to doing in Java. ``` square(4) ``` ## Tests CSCI0200 will put a lot of emphasis on writing tests. A collection of tests go into a `check` block. The two expressions on either side of the `is` are compared for structural equality. ```=pyret check: square(6) is 36 square(0.5) is 0.25 end ``` ## Lists Lists are built in: ``` shopping = [list: "milk", "pie", "bread"] ``` Lists are actually objects in Pyret. You can write expressions over them using either function-notation or method-notation: ``` length(shopping) shopping.length() # note here that length is a method, not a field ``` You can get at elements of lists using `first` to get the first element and `rest` to get the list without the first element. ``` check: shopping.first is "milk" shopping.rest is [list: "pie", "bread"]] shopping.rest.first is "pie" end ``` We don't have to write these list expressions in a `check` block, but we did so here to show you the result of using the list operators in a way that would run in Pyret. Here is the Pyret documentation with the [collection of built-in (functions and methods) on lists](https://www.pyret.org/docs/latest/lists.html) (down the left sidebar). ## Functions as Arguments One hallmark of functional programming is that functions can be passed as arguments and returned as the results of functions. Here's an example from the Pyret documentation that shows how to specify criteria for sorting a list: ```=pyret a-list = [list: 'a', 'aa', 'aaa'] check: fun length-comparison(s1 :: String, s2 :: String) -> Boolean: string-length(s1) > string-length(s2) end fun length-equality(s1 :: String, s2 :: String) -> Boolean: string-length(s1) == string-length(s2) end a-list.sort-by(length-comparison, length-equality) is [list: 'aaa', 'aa', 'a'] end ``` Sometimes, when we pass a function as an argument, we don't want to bother naming it. Then, we can use a construct called `lambda` that defines a function but without giving it a name: ```=pyret [list: "ab", "a", "", "c"].filter(lam(str): string-length(str) == 1 end) ``` ## Datatypes A datatype describes the name and fields of a class (you are used to calling fields *instance variables*, but functional programming talks more in terms of structure of data and doesn't emphasize mutation). Here are two examples: a `cage` is like a method-less class with two fields. `boa` and `dillo` are two kinds of `Animal`. Here, `Animal` is a type name, a role that interfaces can play in Java. `boa` and `dillo` name constructors that return values of type `Animal`. Pyret generates constructors and getters automatically from a `data` description. ```=pyret data Cage: cage(width :: Number, height :: Number) end data Animal: | boa(name :: String, length :: Number, eats :: String) | dillo(length :: Number, isDead :: Boolean) end # Examples of animals veggie-boa = boa("slim", 24, "lettuce") big-boa = boa("burk", 40, "cars") dead-dillo = dillo(5, true) ``` Here's how to write a function over multiple variants of the same type. `Cases` is like a special/custom kind of if-statement that just serves to break down data types that have fields. Within the line for each constructor, the names in parens after the constructor (like `nm, len, eats` in `boa`) give local names to the field values within the value passed as `ani`. ```=pyret fun fits-in(ani :: Animal, cg :: Cage): Boolean -> doc: "determine whether cage accomodates animal based on length" cases (Animal) ani: | boa(nm, len, eats) => (len < (cg.width / 3)) | dillo(len, isDead) => (len < cg.width) end end ``` Often, we make lists of datatype values: ``` zoo = [list: dead-dillo, big-boa, veggie-boa] ``` ## Conditionals Sometimes, you just need an `if-else` as part of the logic of your program: ```=pyret temp = 50 if temp > 100: "hot" else if temp > 75: "nice" else: "too cold for me" end ``` The value of the if-expression is the value of the answer for the first test that returns true. ## Images Pyret has some fun features that we won't use in 200, but that you could use to practice these early coding concepts if you'd like. Check out the [images library](https://www.pyret.org/docs/latest/image.html#%28part._.Polygons%29). ```=pyret above( star(50, "solid", "purple"), rectangle(200,100, "outline", "green")) ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully