Writing Clojure with Vim

Total Page:16

File Type:pdf, Size:1020Kb

Writing Clojure with Vim APPENDIX A Conventions Every programming language has its own conventions for ensuring a collective understanding and consistency with the design of code written in that language. Some conventions are also able to transition pretty consistently across different programming languages due to the fact that there are groupings of languages (such as C) where the syntax is similar, and so the conventions make sense when applied across multiple languages. For example, if you’ve ever written a for loop (of any variety), then chances are you’ll know of the variable identifiers i, j, and k being used as characters for each nested loop level (see Listing A-1, which utilizes the JavaScript language syntax to demonstrate a for loop). Listing A-1. Example of i, j, and k Variables in a for Loop for (i = 0; i < condition; i++) { for (j = 0; j < condition; j++) { for (k = 0; k < condition; k++) { // code } } } ■■Note i, j, and k are typically used for a few reasons (depending on who you talk to): i and j have been used in mathematics for a very long time, and so the transition of math to programming persisted. On a practical level, i is sometimes interpreted to stand for integer, and so when needing a nested level, it made sense to start moving up the alphabet to j, then k. Clojure has similar naming conventions. © Mark McDonnell 2017 185 M. McDonnell, Quick Clojure, DOI 10.1007/978-1-4842-2952-1 APPENDIX A ■ CoNVENTIoNS Functions • f, g, h: function input (notice similarity with i, j, k, where now f represents function) • n: integer input (usually a size) • i: integer index • x, y: numbers • s: string input • xs: considered a plural, or sequence, of x • coll: a collection (or sequence) • pred: a predicate closure • & more: variadic input • *var*: dynamic variables should be wrapped in asterisks (also referred to as “ear muffs”) Macros • expr: an expression • body: a macro body • binding: a macro binding vector 186 APPENDIX B Writing Clojure with Vim There are many text/code editors available on the market, each with its pros and cons and justifications as to why you should use it. Here is a short list that I managed to put together of editors that had some form of Clojure support available within them (or via plugins): • Atom: Proto REPL • Emacs: CIDER • Vim: Fireplace • IntelliJ (Java IDE): Cursive • Light Table: Built-in Interactive Clojure IDE As you can probably tell by the title of this appendix, I’m a Vim user. Now, I’m not going to sell you on the virtues of why I feel Vim is the best editor to use, as I’ve already done that by writing a book on the topic called Pro Vim1 (published by Apress). Also, Vim does have quite a steep learning curve, so it’s not ideal for everyone. That being said, if you’re interested in using Vim for Clojure and/or you’re already a Vim user, then stick with me while I cover the different plugins and configuration settings you’ll need in order to get working efficiently with Clojure in Vim. To start with, we need the following plugins installed: • vim-fireplace2 • vim-sexp-mappings-for-regular-people3 • rainbow_parentheses.vim4 Now I'm going to run through these plugins in reverse order, because the preceding list is actually in priority order (i.e., the Fireplace plugin is essential, but the next two plugins, although very useful, strictly speaking aren’t “essential” in order to have something working). 1http://www.apress.com/gb/book/9781484202517 2https://github.com/tpope/vim-fireplace/ 3https://github.com/tpope/vim-sexp-mappings-for-regular-people/ 4https://github.com/kien/rainbow_parentheses.vim © Mark McDonnell 2017 187 M. McDonnell, Quick Clojure, DOI 10.1007/978-1-4842-2952-1 APPENDIX B ■ WRITING CLOJURE wITH VIM But also, the complexity of each plugin matches its priority and importance. So, for example, the lowest-priority plugin, Rainbow Parentheses, is also the easiest to describe. Rainbow Parentheses This plugin is very easy to work with. It takes all your boring parentheses and makes them color coded (that’s it). The point is to make it easier to decipher the start and end of a particular Clojure form. You might wonder: Why bother? But trust me, even with a Clojure file format theme, your eyes will still struggle to pick out specific forms in your code (especially because as your code becomes more complex you’ll find there are lots of nested parentheses to deal with), and so having them rainbow colored is a real blessing. Sexp Mappings for Regular People In a Lisp-based language, you have what are referred to as S-expressions.5 In layman’s terms, these are simply part of a notation format, and you see them in Lisp-based languages as parentheses wrapped around expressions (this comes back to the “code as data” mantra we discussed at the beginning of the book, where code represents the same underlying data structure). So, this plugin allows you to manipulate your Clojure code (e.g., the Clojure “forms”). But it’s important to not get this plugin confused with another Vim plugin called Sexp,6 which is a valid plugin for manipulating S-expressions. But the plugin we’re interested in here is actually an extension of Sexp, just with more idiomatic key bindings for terminal- based Vim users. There are two primary functions of this plugin: 1. Automatic Parentheses Matching 2. List Manipulation The first item is fairly straightforward: if you type an opening parenthesis (, then Vim will automatically insert a closing parenthesis ) after it and will then place your cursor in-between the parentheses. This is great because it saves you from forgetting to add either an opening or closing parenthesis yourself, which could accidentally cause your program to trigger an error (this can be quite an annoying bug to have to fix, as it can be difficult to identify when dealing with heavily nested forms). The second item, list manipulation, is the crux of this plugin. It provides the following key bindings: • <f and >f: move “form” left or right • <e and >e: move “element” left or right 5https://en.wikipedia.org/wiki/S-expression 6https://github.com/guns/vim-sexp 188 APPENDIX B ■ WRITING CLOJURE wITH VIM • <( and >(: move “opening parenthesis” left or right • <) and >): move “closing parenthesis” left or right • <I and >I: move “insertion” left or right Let’s do some quick demonstrations to highlight how these key bindings work. We’ll assume we’re dealing with the following code (see Listing B-1), and after each manipulation we’ll compare back to Listing B-1 to see how things have changed. Listing B-1. A Simple Function That Handles a Calculation (def myfn [f g h] (* h (+ f g))) Form Manipulation The key bindings <f and >f affect the innermost form your cursor currently resides within. So, if your cursor is inside (or on top of) the form (+ f g) and you execute <f, then you’ll find that the form moves to the left (see Listing B-2 for the new layout). Listing B-2. Result from Form Manipulation (def myfn [f g h] (* (+ f g) h)) Element Manipulation Similar to form manipulation, if your cursor is on top of the h symbol (i.e., “element”) and you execute >e on the original example code, then you’ll find that it moves the element to the right (see Listing B-3 for the new layout). Listing B-3. Result from Element Manipulation (def myfn [f g h] (* (+ f g) h)) ■■Note You’ll see that Listing B-3 reached the same output as Listing B-2, but it was achieved by two different mechanisms. Parenthesis Manipulation If your cursor is on top of (or inside of) the ( character from (+ f g), and you execute 2<( on the original example code, then you’ll find that it moves the parenthesis two places to the left (see Listing B-4 for the new layout). In this example, I’ve used a Vim count of 2 with <(, so it is run twice. 189 APPENDIX B ■ WRITING CLOJURE wITH VIM Listing B-4. Result from Parenthesis Manipulation (def myfn [f g h] ((* h + f g))) ■■Note This code would now cause an error when run, but I’ve done this to demonstrate the functionality (because of the automatic parenthesis-insertion feature, I very rarely need to manipulate an individual parenthesis). Insertion Manipulation If your cursor is on top of (or inside of) a form, then executing <I will move your cursor to the start of the form and automatically enter Vim’s INSERT mode. As an example, place your cursor inside (+ f g) and execute <I; you should see that the cursor is placed before the +, ready for you to start typing. Similarly, if you were to place your cursor inside the (* h ...), making sure it’s outside of the (+ f g) form (which is nested inside), and then execute >I; you would see that the cursor is placed just before the form’s closing parenthesis. This feature is useful for quickly getting to the start and end of long and complex forms. Fireplace The Fireplace plugin is the main event. With this plugin, you can connect Vim to a networked REPL (Leiningen, in our case, but there are others you can use if you want to) and dynamically evaluate your Clojure code right from within Vim. This would result in your getting instant feedback on the code you’ve written and how it will actually behave.
Recommended publications
  • Lecture 4. Higher-Order Functions Functional Programming
    Lecture 4. Higher-order functions Functional Programming [Faculty of Science Information and Computing Sciences] 0 I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state [Faculty of Science Information and Computing Sciences] 1 I (almost) unique types I no inheritance hell I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto [Faculty of Science Information and Computing Sciences] 1 I high-level declarative data-structures I no explicit reference-based data structures Goal of typed purely functional programming Keep programs easy to reason about by I data-flow only through function arguments and return values I no hidden data-flow through mutable variables/state I function call and return as only control-flow primitive I no loops, break, continue, goto I (almost) unique types I no inheritance hell [Faculty of Science Information and Computing Sciences] 1 Goal
    [Show full text]
  • Clojure.Core 12
    clojure #clojure 1 1: Clojure 2 2 2 Examples 3 3 1 : Leiningen 3 3 OS X 3 Homebrew 3 MacPorts 3 Windows 3 2 : 3 3 : 4 ", !" REPL 4 4 ", !" 4 ( ) 5 2: clj-time 6 6 Examples 6 6 - 6 6 6 joda - 7 - - 7 3: Clojure destructuring 8 Examples 8 8 8 9 9 9 fn params 9 10 10 : 10 Key 10 . 11 4: clojure.core 12 12 Examples 12 12 Assoc - / 12 Clojure 12 Dissoc - 13 5: clojure.spec 14 14 14 Examples 14 14 fdef : 14 14 clojure.spec / & clojure.spec / 15 15 16 16 18 6: clojure.test 19 Examples 19 ~. 19 19 deftest 19 20 . 20 Leiningen 20 7: core.async 22 Examples 22 : , , , . 22 chan 22 >!! >!! >! 22 <!! <!! 23 23 put! 24 take! 24 24 8: core.match 26 26 Examples 26 26 26 26 26 9: Java interop 27 27 27 Examples 27 Java 27 Java 27 Java 27 27 Clojure 28 10: 29 29 29 Examples 29 29 11: 30 Examples 30 30 30 31 IntelliJ IDEA + 31 Spacemacs + CIDER 31 32 12: 33 Examples 33 33 . 33 33 34 34 34 34 34 35 35 13: 36 36 36 Examples 36 36 36 14: 38 38 38 Examples 38 38 15: 39 39 Examples 39 (- >>) 39 (->) 39 (as->) 39 16: 40 40 Examples 40 40 40 40 17: 41 Examples 41 http-kit 41 Luminus 41 42 42 42 18: CIDER 43 43 Examples 43 43 43 19: 45 Examples 45 45 45 20: 46 46 Examples 46 46 46 48 52 55 58 21: 63 Examples 63 & 63 22: 64 64 64 Examples 64 64 64 / 65 23: 66 Examples 66 66 : 66 67 You can share this PDF with anyone you feel could benefit from it, downloaded the latest version from: clojure It is an unofficial and free clojure ebook created for educational purposes.
    [Show full text]
  • Higher-Order Functions 15-150: Principles of Functional Programming – Lecture 13
    Higher-order Functions 15-150: Principles of Functional Programming { Lecture 13 Giselle Reis By now you might feel like you have a pretty good idea of what is going on in functional program- ming, but in reality we have used only a fragment of the language. In this lecture we see what more we can do and what gives the name functional to this paradigm. Let's take a step back and look at ML's typing system: we have basic types (such as int, string, etc.), tuples of types (t*t' ) and functions of a type to a type (t ->t' ). In a grammar style (where α is a basic type): τ ::= α j τ ∗ τ j τ ! τ What types allowed by this grammar have we not used so far? Well, we could, for instance, have a function below a tuple. Or even a function within a function, couldn't we? The following are completely valid types: int*(int -> int) int ->(int -> int) (int -> int) -> int The first one is a pair in which the first element is an integer and the second one is a function from integers to integers. The second one is a function from integers to functions (which have type int -> int). The third type is a function from functions to integers. The two last types are examples of higher-order functions1, i.e., a function which: • receives a function as a parameter; or • returns a function. Functions can be used like any other value. They are first-class citizens. Maybe this seems strange at first, but I am sure you have used higher-order functions before without noticing it.
    [Show full text]
  • Metadefender Core V4.12.2
    MetaDefender Core v4.12.2 © 2018 OPSWAT, Inc. All rights reserved. OPSWAT®, MetadefenderTM and the OPSWAT logo are trademarks of OPSWAT, Inc. All other trademarks, trade names, service marks, service names, and images mentioned and/or used herein belong to their respective owners. Table of Contents About This Guide 13 Key Features of Metadefender Core 14 1. Quick Start with Metadefender Core 15 1.1. Installation 15 Operating system invariant initial steps 15 Basic setup 16 1.1.1. Configuration wizard 16 1.2. License Activation 21 1.3. Scan Files with Metadefender Core 21 2. Installing or Upgrading Metadefender Core 22 2.1. Recommended System Requirements 22 System Requirements For Server 22 Browser Requirements for the Metadefender Core Management Console 24 2.2. Installing Metadefender 25 Installation 25 Installation notes 25 2.2.1. Installing Metadefender Core using command line 26 2.2.2. Installing Metadefender Core using the Install Wizard 27 2.3. Upgrading MetaDefender Core 27 Upgrading from MetaDefender Core 3.x 27 Upgrading from MetaDefender Core 4.x 28 2.4. Metadefender Core Licensing 28 2.4.1. Activating Metadefender Licenses 28 2.4.2. Checking Your Metadefender Core License 35 2.5. Performance and Load Estimation 36 What to know before reading the results: Some factors that affect performance 36 How test results are calculated 37 Test Reports 37 Performance Report - Multi-Scanning On Linux 37 Performance Report - Multi-Scanning On Windows 41 2.6. Special installation options 46 Use RAMDISK for the tempdirectory 46 3. Configuring Metadefender Core 50 3.1. Management Console 50 3.2.
    [Show full text]
  • Clojure, Given the Pun on Closure, Representing Anything Specific
    dynamic, functional programming for the JVM “It (the logo) was designed by my brother, Tom Hickey. “It I wanted to involve c (c#), l (lisp) and j (java). I don't think we ever really discussed the colors Once I came up with Clojure, given the pun on closure, representing anything specific. I always vaguely the available domains and vast emptiness of the thought of them as earth and sky.” - Rich Hickey googlespace, it was an easy decision..” - Rich Hickey Mark Volkmann [email protected] Functional Programming (FP) In the spirit of saying OO is is ... encapsulation, inheritance and polymorphism ... • Pure Functions • produce results that only depend on inputs, not any global state • do not have side effects such as Real applications need some changing global state, file I/O or database updates side effects, but they should be clearly identified and isolated. • First Class Functions • can be held in variables • can be passed to and returned from other functions • Higher Order Functions • functions that do one or both of these: • accept other functions as arguments and execute them zero or more times • return another function 2 ... FP is ... Closures • main use is to pass • special functions that retain access to variables a block of code that were in their scope when the closure was created to a function • Partial Application • ability to create new functions from existing ones that take fewer arguments • Currying • transforming a function of n arguments into a chain of n one argument functions • Continuations ability to save execution state and return to it later think browser • back button 3 ..
    [Show full text]
  • Topic 6: Partial Application, Function Composition and Type Classes
    Recommended Exercises and Readings Topic 6: Partial Application, • From Haskell: The craft of functional programming (3rd Ed.) Function Composition and Type • Exercises: • 11.11, 11.12 Classes • 12.30, 12.31, 12.32, 12.33, 12.34, 12.35 • 13.1, 13.2, 13.3, 13.4, 13.7, 13.8, 13.9, 13.11 • If you have time: 12.37, 12.38, 12.39, 12.40, 12.41, 12.42 • Readings: • Chapter 11.3, and 11.4 • Chapter 12.5 • Chapter 13.1, 13.2, 13.3 and 13.4 1 2 Functional Forms Curried and Uncurried Forms • The parameters to a function can be viewed in two different ways • Uncurried form • As a single combined unit • Parameters are bundled into a tuple and passed as a group • All values are passed as one tuple • Can be used in Haskell • How we typically think about parameter passing in Java, C++, Python, Pascal, C#, … • Typically only when there is a specific need to do • As a sequence of values that are passed one at a time • As each value is passed, a new function is formed that requires one fewer parameters • Curried form than its predecessor • Parameters are passed to a function sequentially • How parameters are passed in Haskell • Standard form in Haskell • But it’s not a detail that we need to concentrate on except when we want to make use of it • Functions can be transformed from one form to the other 3 4 Curried and Uncurried Forms Curried and Uncurried Forms • A function in curried form • Why use curried form? • Permits partial application multiply :: Int ‐> Int ‐> Int • Standard way to define functions in Haskell multiply x y = x * y • A function of n+1
    [Show full text]
  • Basic Guide: Using VIM Introduction: VI and VIM Are In-Terminal Text Editors That Come Standard with Pretty Much Every UNIX Op
    Basic Guide: Using VIM Introduction: VI and VIM are in-terminal text editors that come standard with pretty much every UNIX operating system. Our Astro computers have both. These editors are an alternative to using Emacs for editing and writing programs in python. VIM is essentially an extended version of VI, with more features, so for the remainder of this discussion I will be simply referring to VIM. (But if you ever do research and need to ssh onto another campus’s servers and they only have VI, 99% of what you know will still apply). There are advantages and disadvantages to using VIM, just like with any text editors. The main disadvantage of VIM is that it has a very steep learning curve, because it is operated via many keyboard shortcuts with somewhat obscure names like dd, dw, d}, p, u, :q!, etc. In addition, although VIM will do syntax highlighting for Python (ie, color code things based on what type of thing they are), it doesn’t have much intuitive support for writing long, extensive, and complex codes (though if you got comfortable enough you could conceivably do it). On the other hand, the advantage of VIM is once you learn how to use it, it is one of the most efficient ways of editing text. (Because of all the shortcuts, and efficient ways of opening and closing). It is perfectly reasonable to use a dedicated program like emacs, sublime, canopy, etc., for creating your code, and learning VIM as a way to edit your code on the fly as you try to run it.
    [Show full text]
  • EHR Usability Test Report of Pediatricxpress, Version 20
    Page | 1 EHR Usability Test Report of PediatricXpress, Version 20 Report based on ISO/IEC 25062:2006 Common Industry Format for Usability Test Reports Date of Usability Test: January 30, 2019 – February 8, 2019 Date of Report: February 11, 2019 (updated 10/28/20) Report Prepared by: PhysicianXpress, Inc. Vene Quezada, Product Specialist [email protected] 877-366-7331 409 2nd Avenue, Suite 201 Collegeville, PA 19426 Page | 2 Table of Contents 1 EXECUTIVE SUMMARY 3 2 INTRODUCTION 10 3 METHOD 10 3.1 PARTICIPANTS 10 3.2 STUDY DESIGN 12 3.3 TASKS 13 3.4 RISK ASSESSMENT 1 4 3.4 PROCEDURE 15 3.5 TEST LOCATION 16 3.6 TEST ENVIRONMENT 16 3.7 TEST FORMS AND TOOLS 17 3.8 PARTICIPANT INSTRUCTIONS 17 3.9 USABILITY METRICS 19 3.10 DATA SCORING 20 4 RESULTS 21 4.1 DATA ANALYSIS AND REPORTING 21 4.2 DISCUSSION OF THE FINDINGS 25 5 APPENDICES 29 5.1 Appendix 1: Participant Demographics 30 5.2 Appendix 2: Informed Consent Form 31 5.3 Appendix 3: Example Moderator’s guide 32 5.4 Appendix 4: System Usability Scale questionnaire 43 5.5 Appendix 5: Acknowledgement Form 44 Page | 3 EXECUTIVE SUMMARY A usability test of PediatricXpress, version 20, ambulatory E.H.R. was conducted on selected features of the PediatricXpress version 20 E.H.R. as part of the Safety- Enhanced Design requirements outlined in 170.315(g)(3) between January 30th , 2019 and February 8, 2019 at 409 2nd Avenue, Collegeville, PA 19426. The purpose of this testing was to test and validate the usability of the current user interface and provide evidence of usability in the EHR Under Test (EHRUT).
    [Show full text]
  • Functional Programming Lecture 1: Introduction
    Functional Programming Lecture 13: FP in the Real World Viliam Lisý Artificial Intelligence Center Department of Computer Science FEE, Czech Technical University in Prague [email protected] 1 Mixed paradigm languages Functional programming is great easy parallelism and concurrency referential transparency, encapsulation compact declarative code Imperative programming is great more convenient I/O better performance in certain tasks There is no reason not to combine paradigms 2 3 Source: Wikipedia 4 Scala Quite popular with industry Multi-paradigm language • simple parallelism/concurrency • able to build enterprise solutions Runs on JVM 5 Scala vs. Haskell • Adam Szlachta's slides 6 Is Java 8 a Functional Language? Based on: https://jlordiales.me/2014/11/01/overview-java-8/ Functional language first class functions higher order functions pure functions (referential transparency) recursion closures currying and partial application 7 First class functions Previously, you could pass only classes in Java File[] directories = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.isDirectory(); } }); Java 8 has the concept of method reference File[] directories = new File(".").listFiles(File::isDirectory); 8 Lambdas Sometimes we want a single-purpose function File[] csvFiles = new File(".").listFiles(new FileFilter() { @Override public boolean accept(File pathname) { return pathname.getAbsolutePath().endsWith("csv"); } }); Java 8 has lambda functions for that File[] csvFiles = new File(".")
    [Show full text]
  • Appendix a the Ten Commandments for Websites
    Appendix A The Ten Commandments for Websites Welcome to the appendixes! At this stage in your learning, you should have all the basic skills you require to build a high-quality website with insightful consideration given to aspects such as accessibility, search engine optimization, usability, and all the other concepts that web designers and developers think about on a daily basis. Hopefully with all the different elements covered in this book, you now have a solid understanding as to what goes into building a website (much more than code!). The main thing you should take from this book is that you don’t need to be an expert at everything but ensuring that you take the time to notice what’s out there and deciding what will best help your site are among the most important elements of the process. As you leave this book and go on to updating your website over time and perhaps learning new skills, always remember to be brave, take risks (through trial and error), and never feel that things are getting too hard. If you choose to learn skills that were only briefly mentioned in this book, like scripting, or to get involved in using content management systems and web software, go at a pace that you feel comfortable with. With that in mind, let’s go over the 10 most important messages I would personally recommend. After that, I’ll give you some useful resources like important websites for people learning to create for the Internet and handy software. Advice is something many professional designers and developers give out in spades after learning some harsh lessons from what their own bitter experiences.
    [Show full text]
  • Notes on Functional Programming with Haskell
    Notes on Functional Programming with Haskell H. Conrad Cunningham [email protected] Multiparadigm Software Architecture Group Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA Fall Semester 2014 Copyright c 1994, 1995, 1997, 2003, 2007, 2010, 2014 by H. Conrad Cunningham Permission to copy and use this document for educational or research purposes of a non-commercial nature is hereby granted provided that this copyright notice is retained on all copies. All other rights are reserved by the author. H. Conrad Cunningham, D.Sc. Professor and Chair Department of Computer and Information Science University of Mississippi 201 Weir Hall University, Mississippi 38677 USA [email protected] PREFACE TO 1995 EDITION I wrote this set of lecture notes for use in the course Functional Programming (CSCI 555) that I teach in the Department of Computer and Information Science at the Uni- versity of Mississippi. The course is open to advanced undergraduates and beginning graduate students. The first version of these notes were written as a part of my preparation for the fall semester 1993 offering of the course. This version reflects some restructuring and revision done for the fall 1994 offering of the course|or after completion of the class. For these classes, I used the following resources: Textbook { Richard Bird and Philip Wadler. Introduction to Functional Program- ming, Prentice Hall International, 1988 [2]. These notes more or less cover the material from chapters 1 through 6 plus selected material from chapters 7 through 9. Software { Gofer interpreter version 2.30 (2.28 in 1993) written by Mark P.
    [Show full text]
  • Currying and Partial Application and Other Tasty Closure Recipes
    CS 251 Fall 20192019 Principles of of Programming Programming Languages Languages λ Ben Wood Currying and Partial Application and other tasty closure recipes https://cs.wellesley.edu/~cs251/f19/ Currying and Partial Application 1 More idioms for closures • Function composition • Currying and partial application • Callbacks (e.g., reactive programming, later) • Functions as data representation (later) Currying and Partial Application 2 Function composition fun compose (f,g) = fn x => f (g x) Closure “remembers” f and g : ('b -> 'c) * ('a -> 'b) -> ('a -> 'c) REPL prints something equivalent ML standard library provides infix operator o fun sqrt_of_abs i = Math.sqrt(Real.fromInt(abs i)) fun sqrt_of_abs i = (Math.sqrt o Real.fromInt o abs) i val sqrt_of_abs = Math.sqrt o Real.fromInt o abs Right to left. Currying and Partial Application 3 Pipelines (left-to-right composition) “Pipelines” of functions are common in functional programming. infix |> fun x |> f = f x fun sqrt_of_abs i = i |> abs |> Real.fromInt |> Math.sqrt (F#, Microsoft's ML flavor, defines this by default) Currying and Partial Application 4 Currying • Every ML function takes exactly one argument • Previously encoded n arguments via one n-tuple • Another way: Take one argument and return a function that takes another argument and… – Called “currying” after logician Haskell Curry Currying and Partial Application 6 Example val sorted3 = fn x => fn y => fn z => z >= y andalso y >= x val t1 = ((sorted3 7) 9) 11 • Calling (sorted3 7) returns a closure with: – Code fn y => fn z
    [Show full text]