![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']](https://data.docslib.org/img/3a60ab92a6e30910dab9bd827208bcff-1.webp)
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.
Details
-
File Typepdf
-
Upload Time-
-
Content LanguagesEnglish
-
Upload UserAnonymous/Not logged-in
-
File Pages13 Page
-
File Size-