Haskell Cheat Sheet Strings Enumerations • "Abc" – Unicode String, Sugar for This Cheat Sheet Lays out the Fundamental Ele- • [1..10] 1, 2, , 10 ['A','B','C']

Total Page:16

File Type:pdf, Size:1020Kb

Haskell Cheat Sheet Strings Enumerations • Haskell Cheat Sheet Strings Enumerations • "abc" – Unicode string, sugar for This cheat sheet lays out the fundamental ele- • [1..10] 1, 2, , 10 ['a','b','c']. – List of numbers – ... ments of the Haskell language: syntax, keywords • [100..] 100, • 'a' – Single character. – Infinite list of numbers – and other elements. It is presented as both an ex- 101, 102, .... ecutable Haskell file and a printable document. • [110..100] – Empty list; ranges only go for- Multi-line Strings Normally, it is a syntax error Load the source into your favorite interpreter to wards. if a string has any actual newline characters. That play with code samples shown. • [0, -1 ..] – Negative integers. is, this is a syntax error: • [-100..-110] – Syntax error; need string1 = "My long [-100.. -110] for negatives. Basic Syntax string." • [1,3..100], [-1,3..100] – List from 1 to 100 by 2, -1 to 100 by 4. Backslashes (‘\’) can “escape” a newline: Comments In fact, any value which is in the Enum class can be string1 = "My long \ used: A single line comment starts with ‘--’ and extends \string." • ['a' .. 'z'] – List of characters – a, b, to the end of the line. Multi-line comments start ..., z. with ’{-’ and extend to ’-}’. Comments can be The area between the backslashes is ignored. • [1.0, 1.5 .. 2] – [1.0,1.5,2.0]. nested. Newlines in the string must be represented explic- • [UppercaseLetter ..] itly: – List of Comments above function definitions should GeneralCategory Data.Char {- | values (from ). start with ‘ ’ and those next to parameter types string2 = "My long \n\ -- ^ with ‘ ’ for compatibility with Haddock, a sys- \string." tem for documenting Haskell code. That is, string1 evaluates to: Lists & Tuples Reserved Words My long string. • [] – Empty list. While string2 evaluates to: The following words are reserved in Haskell. It is • [1,2,3] – List of three numbers. a syntax error to give a variable or a function one My long • 1 : 2 : 3 : [] – Alternate way to write of these names. string. lists using “cons” (:) and “nil” ([]). • "abc" – List of three characters (strings are • case • import • of Numbers lists). • class • in • module • 'a' : 'b' : 'c' : [] – List of characters • data • infix • newtype • 1 – Integer or Floating point (same as "abc"). • deriving • infixl • then • 1.0, 1e10 – Floating point • (1,"a") – 2-element tuple of a number and • do • infixr • type • 1. – syntax error a string. • else • instance • where • -1 – sugar for (negate 1) • (head, tail, 3, 'a') – 4-element tuple of • if • let • 2-1 – sugar for ((-) 2 1) two functions, a number and a character. c 2009 Justin Bailey. 1 [email protected] “Layout” rule, braces and semi-colons. Let Indent the body of the let at least one space Nesting & Capture Nested matching and bind- from the first definition in the let. If let appears ing are also allowed. Haskell can be written using braces and semi- on its own line, the body of any definition must data Maybe a = Just a | Nothing colons, just like C. However, no one does. Instead, appear in the column after the let: the “layout” rule is used, where spaces represent scope. The general rule is: always indent. When square x = Maybe the compiler complains, indent more. let x2 = Figure 1: The definition of x * x in x2 Using Maybe we can determine if any choice Braces and semi-colons Semi-colons termi- was given using a nested match: nate an expression, and braces represent scope. As can be seen above, the in keyword must also be They can be used after several keywords: where, in the same column as let. Finally, when multiple anyChoice1 ch = let, do and of. They cannot be used when defin- definitions are given, all identifiers must appear in case ch of ing a function body. For example, the below will the same column. Nothing -> "No choice!" not compile. Just (First _) -> "First!" Just Second -> "Second!" square2 x = { x * x; } Keywords _ -> "Something else." Haskell keywords are listed below, in alphabetical However, this will work fine: Binding can be used to manipulate the value order. matched: square2 x = result anyChoice2 ch = where { result = x * x; } Case case ch of case is similar to a switch statement in C# or Java, Nothing -> "No choice!" Function Definition Indent the body at least but can match a pattern: the shape of the value be- Just score@(First "gold") -> one space from the function name: ing inspected. Consider a simple data type: "First with gold!" data Choices = First String | Second | Just score@(First _) -> square x = Third | Fourth "First with something else: " x * x ++ show score case can be used to determine which choice was _ -> "Not first." Unless a where clause is present. In that case, in- given: dent the where clause at least one space from the whichChoice ch = Matching Order Matching proceeds from top function name and any function bodies at least case ch of to bottom. If anyChoice1 is reordered as follows, one space from the where keyword: First _ -> "1st!" the first pattern will always succeed: Second -> "2nd!" square x = anyChoice3 ch = _ -> "Something else." x2 case ch of where x2 = As with pattern-matching in function definitions, _ -> "Something else." x * x the ‘_’ token is a “wildcard” matching any value. Nothing -> "No choice!" c 2009 Justin Bailey. 2 [email protected] Just (First _) -> "First!" class Flavor a where Data Just Second -> "Second!" flavor :: a -> String So-called algebraic data types can be declared as fol- Notice that the declaration only gives the type lows: Guards Guards, or conditional matches, can be signature of the function—no implementation is used in cases just like function definitions. The data MyType = MyValue1 | MyValue2 given here (with some exceptions, see “Defaults” only difference is the use of the -> instead of on page 3). Continuing, we can define several in- MyType is the type’s name. MyValue1 and =. Here is a simple function which does a case- stances: MyValue are values of the type and are called con- insensitive string match: instance Flavor Bool where structors. Multiple constructors are separated with strcmp s1 s2 = case (s1, s2) of | flavor _ = "sweet" the ‘ ’ character. Note that type and constructor ([], []) -> True names must start with a capital letter. It is a syn- (s1:ss1, s2:ss2) instance Flavor Char where tax error otherwise. | toUpper s1 == toUpper s2 -> flavor _ = "sour" strcmp ss1 ss2 Constructors with Arguments The type above | otherwise -> False Evaluating flavor True gives: is not very interesting except as an enumeration. _ -> False > flavor True Constructors that take arguments can be declared, "sweet" allowing more information to be stored: Class data Point = TwoD Int Int While flavor 'x' gives: A Haskell function is defined to work on a certain | ThreeD Int Int Int type or set of types and cannot be defined more > flavor 'x' Notice that the arguments for each constructor are than once. Most languages support the idea of "sour" type names, not constructors. That means this “overloading”, where a function can have differ- kind of declaration is illegal: ent behavior depending on the type of its argu- Defaults Default implementations can be given ments. Haskell accomplishes overloading through for functions in a class. These are useful when cer- data Poly = Triangle TwoD TwoD TwoD class and instance declarations. A class defines tain functions can be defined in terms of others in instead, the Point type must be used: one or more functions that can be applied to any the class. A default is defined by giving a body types which are members (i.e., instances) of that to one of the member functions. The canonical ex- data Poly = Triangle Point Point Point class. A class is analogous to an interface in Java ample is Eq, which defines /= (not equal) in terms or C#, and instances to a concrete implementation of ==.: Type and Constructor Names Type and con- of the interface. class Eq a where structor names can be the same, because they will A class must be declared with one or more (==) :: a -> a -> Bool never be used in a place that would cause confu- type variables. Technically, Haskell 98 only al- (/=) :: a -> a -> Bool sion. For example: lows one type variable, but most implementations (/=) a b = not (a == b) data User = User String | Admin String of Haskell support so-called multi-parameter type classes, which allow more than one type variable. Recursive definitions can be created, but an which declares a type named User with two con- We can define a class which supplies a flavor instance declaration must always implement at structors, User and Admin. Using this type in a for a given type: least one class member. function makes the difference clear: c 2009 Justin Bailey. 3 [email protected] whatUser (User _) = "normal user." Multiple constructors (of the same type) can use Because seven of these operations are so com- whatUser (Admin _) = "admin user." the same accessor function for values of the same mon, Haskell provides the deriving keyword type, but that can be dangerous if the accessor is which will automatically implement the typeclass Some literature refers to this practice as type pun- not used by all constructors. Consider this rather on the associated type. The seven supported type- ning. contrived example: classes are: Eq, Read, Show, Ord, Enum, Ix, and Bounded data Con = Con { conValue :: String } . Type Variables Declaring so-called polymorphic | Uncon { conValue :: String } Two forms of deriving are possible. The first data types is as easy as adding type variables in | Noncon is used when a type only derives one class: the declaration: data Slot1 a = Slot1 a | Empty1 whichCon con = "convalue is " ++ data Priority = Low | Medium | High conValue con deriving Show This declares a type Slot1 with two constructors, whichCon Noncon Slot1 and Empty1.
Recommended publications
  • ML Module Mania: a Type-Safe, Separately Compiled, Extensible Interpreter
    ML Module Mania: A Type-Safe, Separately Compiled, Extensible Interpreter The Harvard community has made this article openly available. Please share how this access benefits you. Your story matters Citation Ramsey, Norman. 2005. ML Module Mania: A Type-Safe, Separately Compiled, Extensible Interpreter. Harvard Computer Science Group Technical Report TR-11-05. Citable link http://nrs.harvard.edu/urn-3:HUL.InstRepos:25104737 Terms of Use This article was downloaded from Harvard University’s DASH repository, and is made available under the terms and conditions applicable to Other Posted Material, as set forth at http:// nrs.harvard.edu/urn-3:HUL.InstRepos:dash.current.terms-of- use#LAA ¡¢ £¥¤§¦©¨ © ¥ ! " $# %& !'( *)+ %¨,.-/£102©¨ 3¤4#576¥)+ %&8+9©¨ :1)+ 3';&'( )< %' =?>A@CBEDAFHG7DABJILKM GPORQQSOUT3V N W >BYXZ*[CK\@7]_^\`aKbF!^\K/c@C>ZdX eDf@hgiDf@kjmlnF!`ogpKb@CIh`q[UM W DABsr!@k`ajdtKAu!vwDAIhIkDi^Rx_Z!ILK[h[SI ML Module Mania: A Type-Safe, Separately Compiled, Extensible Interpreter Norman Ramsey Division of Engineering and Applied Sciences Harvard University Abstract An application that uses an embedded interpreter is writ- ten in two languages: Most code is written in the original, The new embedded interpreter Lua-ML combines extensi- host language (e.g., C, C++, or ML), but key parts can be bility and separate compilation without compromising type written in the embedded language. This organization has safety. The interpreter’s types are extended by applying a several benefits: sum constructor to built-in types and to extensions, then • Complex command-line arguments aren’t needed; the tying a recursive knot using a two-level type; the sum con- embedded language can be used on the command line.
    [Show full text]
  • ECSS-E-TM-40-07 Volume 2A 25 January 2011
    ECSS-E-TM-40-07 Volume 2A 25 January 2011 Space engineering Simulation modelling platform - Volume 2: Metamodel ECSS Secretariat ESA-ESTEC Requirements & Standards Division Noordwijk, The Netherlands ECSS‐E‐TM‐40‐07 Volume 2A 25 January 2011 Foreword This document is one of the series of ECSS Technical Memoranda. Its Technical Memorandum status indicates that it is a non‐normative document providing useful information to the space systems developers’ community on a specific subject. It is made available to record and present non‐normative data, which are not relevant for a Standard or a Handbook. Note that these data are non‐normative even if expressed in the language normally used for requirements. Therefore, a Technical Memorandum is not considered by ECSS as suitable for direct use in Invitation To Tender (ITT) or business agreements for space systems development. Disclaimer ECSS does not provide any warranty whatsoever, whether expressed, implied, or statutory, including, but not limited to, any warranty of merchantability or fitness for a particular purpose or any warranty that the contents of the item are error‐free. In no respect shall ECSS incur any liability for any damages, including, but not limited to, direct, indirect, special, or consequential damages arising out of, resulting from, or in any way connected to the use of this document, whether or not based upon warranty, business agreement, tort, or otherwise; whether or not injury was sustained by persons or property or otherwise; and whether or not loss was sustained from, or arose out of, the results of, the item, or any services that may be provided by ECSS.
    [Show full text]
  • Tierless Web Programming in ML Gabriel Radanne
    Tierless Web programming in ML Gabriel Radanne To cite this version: Gabriel Radanne. Tierless Web programming in ML. Programming Languages [cs.PL]. Université Paris Diderot (Paris 7), 2017. English. tel-01788885 HAL Id: tel-01788885 https://hal.archives-ouvertes.fr/tel-01788885 Submitted on 9 May 2018 HAL is a multi-disciplinary open access L’archive ouverte pluridisciplinaire HAL, est archive for the deposit and dissemination of sci- destinée au dépôt et à la diffusion de documents entific research documents, whether they are pub- scientifiques de niveau recherche, publiés ou non, lished or not. The documents may come from émanant des établissements d’enseignement et de teaching and research institutions in France or recherche français ou étrangers, des laboratoires abroad, or from public or private research centers. publics ou privés. Distributed under a Creative Commons Attribution - NonCommercial - ShareAlike| 4.0 International License Thèse de doctorat de l’Université Sorbonne Paris Cité Préparée à l’Université Paris Diderot au Laboratoire IRIF Ecole Doctorale 386 — Science Mathématiques De Paris Centre Tierless Web programming in ML par Gabriel Radanne Thèse de Doctorat d’informatique Dirigée par Roberto Di Cosmo et Jérôme Vouillon Thèse soutenue publiquement le 14 Novembre 2017 devant le jury constitué de Manuel Serrano Président du Jury Roberto Di Cosmo Directeur de thèse Jérôme Vouillon Co-Directeur de thèse Koen Claessen Rapporteur Jacques Garrigue Rapporteur Coen De Roover Examinateur Xavier Leroy Examinateur Jeremy Yallop Examinateur This work is licensed under a Creative Commons “Attribution- NonCommercial-ShareAlike 4.0 International” license. Abstract Eliom is a dialect of OCaml for Web programming in which server and client pieces of code can be mixed in the same file using syntactic annotations.
    [Show full text]
  • Seaflow Language Reference Manual Rohan Arora, Junyang Jin, Ho Sanlok Lee, Sarah Seidman Ra3091, Jj3132, Hl3436, Ss5311
    Seaflow Language Reference Manual Rohan Arora, Junyang Jin, Ho Sanlok Lee, Sarah Seidman ra3091, jj3132, hl3436, ss5311 1 Introduction 3 2 Lexical Conventions 3 2.1 Comments 3 2.2 Identifiers 3 2.3 Keywords 3 2.4 Literals 3 3 Expressions and Statements 3 3.1 Expressions 4 3.1.1 Primary Expressions 4 3.1.1 Operators 4 3.1.2 Conditional expression 4 3.4 Statements 5 3.4.1 Declaration 5 3.4.2 Immutability 5 3.4.3 Observable re-assignment 5 4 Functions Junyang 6 4.1 Declaration 6 4.2 Scope rules 6 4.3 Higher Order Functions 6 5 Observables 7 5.1 Declaration 7 5.2 Subscription 7 5.3 Methods 7 6 Conversions 9 1 Introduction Seaflow is an imperative language designed to address the asynchronous event conundrum by supporting some of the core principles of ReactiveX and reactive programming natively. Modern applications handle many asynchronous events, but it is difficult to model such applications using programming languages such as Java and JavaScript. One popular solution among the developers is to use ReactiveX implementations in their respective languages to architect event-driven reactive models. However, since Java and JavaScript are not designed for reactive programming, it leads to complex implementations where multiple programming styles are mixed-used. Our goals include: 1. All data types are immutable, with the exception being observables, no pointers 2. The creation of an observable should be simple 3. Natively support core principles in the ReactiveX specification 2 Lexical Conventions 2.1 Comments We use the characters /* to introduce a comment, which terminates with the characters */.
    [Show full text]
  • Lecture Notes on Types for Part II of the Computer Science Tripos
    Q Lecture Notes on Types for Part II of the Computer Science Tripos Prof. Andrew M. Pitts University of Cambridge Computer Laboratory c 2016 A. M. Pitts Contents Learning Guide i 1 Introduction 1 2 ML Polymorphism 6 2.1 Mini-ML type system . 6 2.2 Examples of type inference, by hand . 14 2.3 Principal type schemes . 16 2.4 A type inference algorithm . 18 3 Polymorphic Reference Types 25 3.1 The problem . 25 3.2 Restoring type soundness . 30 4 Polymorphic Lambda Calculus 33 4.1 From type schemes to polymorphic types . 33 4.2 The Polymorphic Lambda Calculus (PLC) type system . 37 4.3 PLC type inference . 42 4.4 Datatypes in PLC . 43 4.5 Existential types . 50 5 Dependent Types 53 5.1 Dependent functions . 53 5.2 Pure Type Systems . 57 5.3 System Fw .............................................. 63 6 Propositions as Types 67 6.1 Intuitionistic logics . 67 6.2 Curry-Howard correspondence . 69 6.3 Calculus of Constructions, lC ................................... 73 6.4 Inductive types . 76 7 Further Topics 81 References 84 Learning Guide These notes and slides are designed to accompany 12 lectures on type systems for Part II of the Cambridge University Computer Science Tripos. The course builds on the techniques intro- duced in the Part IB course on Semantics of Programming Languages for specifying type systems for programming languages and reasoning about their properties. The emphasis here is on type systems for functional languages and their connection to constructive logic. We pay par- ticular attention to the notion of parametric polymorphism (also known as generics), both because it has proven useful in practice and because its theory is quite subtle.
    [Show full text]
  • JNI – C++ Integration Made Easy
    JNI – C++ integration made easy Evgeniy Gabrilovich Lev Finkelstein [email protected] [email protected] Abstract The Java Native Interface (JNI) [1] provides interoperation between Java code running on a Java Virtual Machine and code written in other programming languages (e.g., C++ or assembly). The JNI is useful when existing libraries need to be integrated into Java code, or when portions of the code are implemented in other languages for improved performance. The Java Native Interface is extremely flexible, allowing Java methods to invoke native methods and vice versa, as well as allowing native functions to manipulate Java objects. However, this flexibility comes at the expense of extra effort for the native language programmer, who has to explicitly specify how to connect to various Java objects (and later to disconnect from them, to avoid resource leak). We suggest a template-based framework that relieves the C++ programmer from most of this burden. In particular, the proposed technique provides automatic selection of the right functions to access Java objects based on their types, automatic release of previously acquired resources when they are no longer necessary, and overall simpler interface through grouping of auxiliary functions. Introduction The Java Native Interface1 is a powerful framework for seamless integration between Java and other programming languages (called “native languages” in the JNI terminology). A common case of using the JNI is when a system architect wants to benefit from both worlds, implementing communication protocols in Java and computationally expensive algorithmic parts in C++ (the latter are usually compiled into a dynamic library, which is then invoked from the Java code).
    [Show full text]
  • Difference Between Method Declaration and Signature
    Difference Between Method Declaration And Signature Asiatic and relaxed Dillon still terms his tacheometry namely. Is Tom dirt or hierarchal after Zyrian Nelson hasting so variously? Heterozygous Henrique instals terribly. Chapter 15 Functions. How junior you identify a function? There play an important difference between schedule two forms of code block seeing the. Subroutines in C and Java are always expressed as functions methods which may. Only one params keyword is permitted in a method declaration. Complex constant and so, where you declare checked exception parameters which case, it prompts the method declaration group the habit of control passes the positional. Overview of methods method parameters and method return values. A whole object has the cash public attributes and methods. Defining Methods. A constant only be unanimous a type explicitly by doing constant declaration or. As a stop rule using prototypes is the preferred method as it. C endif Class HelloJNI Method sayHello Signature V JNIEXPORT. Method signature It consists of the method name just a parameter list window of. As I breathe in the difference between static and dynamic binding static methods are. Most electronic signature solutions in the United States fall from this broad. DEPRECATED Method declarations with type constraints and per source filter. Methods and Method Declaration in Java dummies. Class Methods Apex Developer Guide Salesforce Developers. Using function signatures to remove a library method Function signatures are known important snapshot of searching for library functions The F libraries. Many different kinds of parameters with rather subtle semantic differences. For addition as real numbers the distinction is somewhat moot because is.
    [Show full text]
  • Data Types Are Values
    Data Types Are Values James Donahue Alan Demers Data Types Are Values James Donahue Xerox Corporation Palo Alto Research Center 3333 Coyote Hill Road Palo Alto, California 94304 Alan Demers Computer Science Department Cornell University Ithaca, New York 14853 CSL -83-5 March 1984 [P83-00005] © Copyright 1984 ACM. All rights reserved. Reprinted with permission. A bst ract: An important goal of programming language research is to isolate the fundamental concepts of languages, those basic ideas that allow us to understand the relationship among various language features. This paper examines one of these underlying notions, data type, with particular attention to the treatment of generic or polymorphic procedures and static type-checking. A version of this paper will appear in the ACM Transact~ons on Programming Languages and Systems. CR Categories and Subject Descriptors: 0.3 (Programming Languages), 0.3.1 (Formal Definitions and Theory), 0.3.3 (Language Constructs), F.3.2 (Semantics of Programming Languages) Additional Keywords and Phrases: data types, polymorphism XEROX Xerox Corporation Palo Alto Research Center 3333 Coyote Hill Road Palo Alto, California 94304 DATA TYPES ARE VALVES 1 1. Introduction An important goal of programming language research is to isolate the fundamental concepts of languages, those basic ideas that allow us to understand the relationship among various language features. This paper examines one of these underlying notions, data type, and presents a meaning for this term that allows us to: describe a simple treatment of generic or polymorphic procedures that preserves full static type-checking and allows unrestricted use of recursion; and give a precise meaning to the phrase strong typing, so that Language X is strongly typed can be interpreted as a critically important theorem about the semantics of the language.
    [Show full text]
  • Open C++ Tutorial∗
    Open C++ Tutorial∗ Shigeru Chiba Institute of Information Science and Electronics University of Tsukuba [email protected] Copyright c 1998 by Shigeru Chiba. All Rights Reserved. 1 Introduction OpenC++ is an extensible language based on C++. The extended features of OpenC++ are specified by a meta-level program given at compile time. For dis- tinction, regular programs written in OpenC++ are called base-level programs. If no meta-level program is given, OpenC++ is identical to regular C++. The meta-level program extends OpenC++ through the interface called the OpenC++ MOP. The OpenC++ compiler consists of three stages: preprocessor, source-to-source translator from OpenC++ to C++, and the back-end C++ com- piler. The OpenC++ MOP is an interface to control the translator at the second stage. It allows to specify how an extended feature of OpenC++ is translated into regular C++ code. An extended feature of OpenC++ is supplied as an add-on software for the compiler. The add-on software consists of not only the meta-level program but also runtime support code. The runtime support code provides classes and functions used by the base-level program translated into C++. The base-level program in OpenC++ is first translated into C++ according to the meta-level program. Then it is linked with the runtime support code to be executable code. This flow is illustrated by Figure 1. The meta-level program is also written in OpenC++ since OpenC++ is a self- reflective language. It defines new metaobjects to control source-to-source transla- tion. The metaobjects are the meta-level representation of the base-level program and they perform the translation.
    [Show full text]
  • Exploring Languages with Interpreters and Functional Programming Chapter 22
    Exploring Languages with Interpreters and Functional Programming Chapter 22 H. Conrad Cunningham 5 November 2018 Contents 22 Overloading and Type Classes 2 22.1 Chapter Introduction . .2 22.2 Polymorphism in Haskell . .2 22.3 Why Overloading? . .2 22.4 Defining an Equality Class and Its Instances . .4 22.5 Type Class Laws . .5 22.6 Another Example Class Visible ..................5 22.7 Class Extension (Inheritance) . .6 22.8 Multiple Constraints . .7 22.9 Built-In Haskell Classes . .8 22.10Comparison to Other Languages . .8 22.11What Next? . .9 22.12Exercises . 10 22.13Acknowledgements . 10 22.14References . 11 22.15Terms and Concepts . 11 Copyright (C) 2017, 2018, H. Conrad Cunningham Professor of Computer and Information Science University of Mississippi 211 Weir Hall P.O. Box 1848 University, MS 38677 (662) 915-5358 Browser Advisory: The HTML version of this textbook requires use of a browser that supports the display of MathML. A good choice as of November 2018 is a recent version of Firefox from Mozilla. 1 22 Overloading and Type Classes 22.1 Chapter Introduction Chapter 5 introduced the concept of overloading. Chapters 13 and 21 introduced the related concepts of type classes and instances. The goal of this chapter and the next chapter is to explore these concepts in more detail. The concept of type class was introduced into Haskell to handle the problem of comparisons, but it has had a broader and more profound impact upon the development of the language than its original purpose. This Haskell feature has also had a significant impact upon the design of subsequent languages (e.g.
    [Show full text]
  • Bidirectional Typing
    Bidirectional Typing JANA DUNFIELD, Queen’s University, Canada NEEL KRISHNASWAMI, University of Cambridge, United Kingdom Bidirectional typing combines two modes of typing: type checking, which checks that a program satisfies a known type, and type synthesis, which determines a type from the program. Using checking enables bidirectional typing to support features for which inference is undecidable; using synthesis enables bidirectional typing to avoid the large annotation burden of explicitly typed languages. In addition, bidirectional typing improves error locality. We highlight the design principles that underlie bidirectional type systems, survey the development of bidirectional typing from the prehistoric period before Pierce and Turner’s local type inference to the present day, and provide guidance for future investigations. ACM Reference Format: Jana Dunfield and Neel Krishnaswami. 2020. Bidirectional Typing. 1, 1 (November 2020), 37 pages. https: //doi.org/10.1145/nnnnnnn.nnnnnnn 1 INTRODUCTION Type systems serve many purposes. They allow programming languages to reject nonsensical programs. They allow programmers to express their intent, and to use a type checker to verify that their programs are consistent with that intent. Type systems can also be used to automatically insert implicit operations, and even to guide program synthesis. Automated deduction and logic programming give us a useful lens through which to view type systems: modes [Warren 1977]. When we implement a typing judgment, say Γ ` 4 : 퐴, is each of the meta-variables (Γ, 4, 퐴) an input, or an output? If the typing context Γ, the term 4 and the type 퐴 are inputs, we are implementing type checking. If the type 퐴 is an output, we are implementing type inference.
    [Show full text]
  • Let's Get Functional
    5 LET’S GET FUNCTIONAL I’ve mentioned several times that F# is a functional language, but as you’ve learned from previous chapters you can build rich applications in F# without using any functional techniques. Does that mean that F# isn’t really a functional language? No. F# is a general-purpose, multi paradigm language that allows you to program in the style most suited to your task. It is considered a functional-first lan- guage, meaning that its constructs encourage a functional style. In other words, when developing in F# you should favor functional approaches whenever possible and switch to other styles as appropriate. In this chapter, we’ll see what functional programming really is and how functions in F# differ from those in other languages. Once we’ve estab- lished that foundation, we’ll explore several data types commonly used with functional programming and take a brief side trip into lazy evaluation. The Book of F# © 2014 by Dave Fancher What Is Functional Programming? Functional programming takes a fundamentally different approach toward developing software than object-oriented programming. While object-oriented programming is primarily concerned with managing an ever-changing system state, functional programming emphasizes immutability and the application of deterministic functions. This difference drastically changes the way you build software, because in object-oriented programming you’re mostly concerned with defining classes (or structs), whereas in functional programming your focus is on defining functions with particular emphasis on their input and output. F# is an impure functional language where data is immutable by default, though you can still define mutable data or cause other side effects in your functions.
    [Show full text]