Introduction FUNCTIONAL PROGRAMMING. The Problem. The Solution. Graham Hutton. Lecture 9 - Interactive Programs. keyboard. screen
|
|
|
- Darlene Hopkins
- 10 years ago
- Views:
Transcription
1 FUNCTIONAL PROGRAMMING Introduction To date, we have seen how Haskell can be used to write batch programs that take all their inputs at the start and give all their outputs at the end. Graham Hutton inputs batch program outputs Lecture 9 - Interactive Programs However, we would also like to use Haskell to write interactive programs that read from the keyboard and write to the screen, as they are running. keyboard The Problem Haskell programs are pure mathematical functions: Haskell programs have no side effects. inputs interactive program outputs However, reading from the keyboard and writing to the screen are side effects: screen 2 Interactive programs have side effects. 3 The Solution Interactive programs can be written in Haskell by using types to distinguish pure expressions from impure actions that may involve side effects. For example: IO Char The type of actions that return a character. IO a The type of actions that return a value of type a. Note: IO () The type of purely side effecting actions that return no result value. () is the type of tuples with no components. 4 5
2 Primitive Actions The standard library provides a number of actions, including the following three primitives: The action putchar c writes the character c to the screen, and returns no result value: putchar :: Char IO () The action getchar reads a character from the keyboard, echoes it to the screen, and returns the character as its result value: The action return v simply returns the value v, without performing any interaction: getchar :: IO Char return :: a IO a 6 7 Sequencing Actions Note - in a sequence of actions: A sequence of actions can be combined as a single composite action using the keyword do. For example: gettwo :: IO (Char,Char) gettwo do x getchar y getchar return (x,y) Each action must begin in precisely the same column. That is, the layout rule applies. The values returned by intermediate actions are discarded by default, but if required can be named using the operator. The value returned by the last action is the value returned by the sequence as a whole. 8 9 Other Library Actions Writing a string to the screen: Reading a string from the keyboard: getline :: IO String getline do x getchar if x '\n' then return [] else do xs getline return (x:xs) putstr :: String IO () putstr [] return () putstr (x:xs) do putchar x putstr xs Writing a string and moving to a new line: putstrln :: String IO () putstrln xs do putstr xs putchar '\n' 0 2
3 Example For example: We can now define an action that prompts for a string to be entered and displays its length: strlen :: IO () strlen do putstr "Enter a string: " xs getline putstr "The string has " putstr (show (length xs)) putstrln " characters" Note: > strlen Enter a string: hello there The string has characters Evaluating an action executes its side effects, with the final result value being discarded. 2 3 Hangman Consider the following version of hangman: One player secretly types in a word. The other player tries to deduce the word, by entering a sequence of guesses. For each guess, the computer indicates which letters in the secret word occur in the guess. The game ends when the guess is correct. We adopt a top down approach to implementing hangman in Haskell, starting as follows: hangman :: IO () hangman do putstrln "Think of a word: " word sgetline putstrln "Try to guess it:" guess word 4 5 The action sgetline reads a line of text from the keyboard, echoing each character as a dash: sgetline :: IO String sgetline do x getch if x '\n' then do putchar x return [] else do putchar '-' xs sgetline return (x:xs) Note: The action getch reads a character from the keyboard, without echoing it to the screen. This useful action is not part of the standard library, but is a special Hugs primitive that can be imported into a script as follows: primitive getch :: IO Char 6 7 3
4 The function guess is the main loop, which requests and processes guesses until the game ends. The function diff indicates which characters in one string occur in a second string: guess :: String IO () guess word do putstr "> " xs getline if xs word then putstrln "You got it!" else do putstrln (diff word xs) guess word 8 diff :: String String String diff xs ys [if elem x ys then x else '-' x xs] For example: > diff "haskell" "pascal" "-as--ll" 9 If you would like to try out the hangman game for yourself, it is available on our Unix machines: % hugs ~gmh/teaching/fun/source/hangman.hs Exercise Implement the game of nim in Haskell, where the rules of the game are as follows: > hangman Think of a word: Try to guess it: > pascal -as--ll > haskell You got it!! 20 The board comprises five rows of stars: : * * * * * 2: * * * * 3: * * * 4: * * 5: * 2 Two players take it turn about to remove one or more stars from the end of a single row. The winner is the player who removes the last star or stars from the board. Hint: Represent the board as a list of five integers that give the number of stars remaining on each row. For example, the initial board is [5,4,3,2,]. 22 4
5 )8&7,2$/352*5$00,* 7\SH'HFODUDWLRQV,QÃ+DVNHOOÃDÃQHZÃQDPHÃIRUÃDQÃH[LVWLQJÃW\SHÃFDQÃEH GHILQHGÃXVLQJÃDÃW\SHÃGHFODUDWLRQ W\SHÃ6WULQJÃ *UDKDP+XWWRQ /HFWXUH'HILQLQJ7\SHV 7\SHÃGHFODUDWLRQVÃFDQÃEHÃXVHGÃWRÃPDNHÃRWKHUÃW\SHV HDVLHUÃWRÃUHDGÃÃ)RUÃH[DPSOHÃJLYHQ /LNH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ÃQHZÃW\SHÃWRÃUHSUHVHQW VXFKÃELQDU\ÃWUHHVÃFDQÃEHÃGHILQHGÃE\ :HÃFDQÃGHILQHÃDÃIXQFWLRQÃILQGÃWKDWÃGHFLGHVÃLIÃDÃJLYHQ LQWHJHUÃRFFXUVÃLQÃDÃELQDU\ÃWUHH GDWDÃ7UHHÃ Ã/HDIÃ,QW ÃÃÃÃÃÃÃÃÃÃ_ÃRGHÃ7UHHÃ,QWÃ7UHH )RUÃH[DPSOHÃWKHÃWUHHÃRQÃWKHÃSUHYLRXVÃVOLGHÃZRXOG EHÃUHSUHVHQWHGÃDVÃIROORZV ILQGÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃ,QWÃ Ã7UHHÃ Ã%RRO ILQGÃ[Ã/HDIÃQÃÃÃÃÃ Ã[ Q ILQGÃ[ÃRGHÃOÃQÃUÃ Ã[ Q ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃ ÃILQGÃ[ÃO ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃ ÃILQGÃ[ÃU RGHÃRGHÃ/HDIÃÃÃ/HDIÃ ÃÃÃÃÃ ÃÃÃÃÃRGHÃ/HDIÃÃÃ/HDIÃ +RZHYHUÃWKLVÃIXQFWLRQÃVLPSO\ÃWUDYHUVHVÃWKHÃHQWLUH WUHHÃDQGÃKHQFHÃIRUÃRXUÃH[DPSOHÃWUHHÃPD\ÃUHTXLUH XSÃWRÃVHYHQÃFRPSDULVRQVÃWRÃSURGXFHÃDÃUHVXOW
9 RZÃFRQVLGHUÃWKHÃIXQFWLRQÃIODWWHQÃWKDWÃUHWXUQVÃWKH OLVWÃRIÃDOOÃWKHÃLQWHJHUVÃFRQWDLQHGÃLQÃDÃWUHH IODWWHQÃÃÃÃÃÃÃÃÃÃÃÃÃÃ7UHHÃ IODWWHQÃ/HDIÃQÃÃÃÃÃ IODWWHQÃRGHÃOÃQÃUÃ ÃIODWWHQÃO ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃIODWWHQÃU $ÃWUHHÃLVÃDÃVHDUFKÃWUHHÃLIÃLWÃIODWWHQVÃWRÃDÃOLVWÃWKDWÃLV RUGHUHGÃÃ2XUÃH[DPSOHÃWUHHÃLVÃDÃVHDUFKÃWUHHÃDVÃLW 6HDUFKÃWUHHVÃKDYHÃWKHÃLPSRUWDQWÃSURSHUW\ÃWKDWÃZKHQ WU\LQJÃWRÃILQGÃDÃYDOXHÃLQÃDÃWUHHÃZHÃFDQÃDOZD\VÃGHFLGH ZKLFKÃRIÃWKHÃWZRÃVXEWUHHVÃLWÃPD\ÃRFFXUÃLQ ILQGÃ[Ã/HDIÃQÃÃÃÃÃÃÃÃÃÃÃÃ Ã[ Q ILQGÃ[ÃRGHÃOÃQÃUÃ_Ã[ QÃ Ã7UXH ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃ_Ã[QÃÃ ÃILQGÃ[ÃO ÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃÃ_Ã[!QÃÃ ÃILQGÃ[ÃU )RUÃH[DPSOHÃWU\LQJÃWRÃILQGÃDQ\ÃYDOXHÃLQÃRXUÃVHDUFK WUHHÃRQO\ÃWDNHVÃDWÃPRVWÃWKUHHÃFRPSDULVRQV ([HUFLVHV 8VLQJÃUHFXUVLRQÃDQGÃWKHÃIXQFWLRQÃDGGÃGHILQHÃD IXQFWLRQÃWKDWÃPXOWLSOLHVÃWZRÃQDWXUDOÃQXPEHUV 'HILQHÃDÃVXLWDEOHÃIXQFWLRQÃIROGÃIRUÃH[SUHVVLRQV DQGÃJLYHÃDÃIHZÃH[DPSOHVÃRIÃLWVÃXVH $ÃELQDU\ÃWUHHÃLVÃFRPSOHWHÃLIÃWKHÃWZRÃVXEWUHHVÃRI HYHU\ÃQRGHÃDUHÃRIÃHTXDOÃVL]HÃÃ'HILQHÃDÃIXQFWLRQ WKDWÃGHFLGHVÃLIÃDÃELQDU\ÃWUHHÃLVÃFRPSOHWH
10 FUNCTIONAL PROGRAMMING The Hugs Graphics Library GraphicsUtils.hs works within Hugs Written by Alastair Reid, University of Utah Library compatible with Win32 and X Bernhard Reus Lecture - Basic Graphics Graphics as Input/Output Embedded in Haskell IO type A First Example Example on Screen Open a window, print "Hello World" in it and close the window as soon as the user releases a key. helloworld :: IO () helloworld rungraphics ( do w <- openwindow "Hello World Window" (300,300) drawinwindow w (text (00,00) "Hello") drawinwindow w (text (00,200) "World") getkey w closewindow w ) 2 3 As graphics are IO one can use the do syntax for sequences of Graphic actions drawinwindow :: Window -> Graphic -> IO () rungraphics :: IO () -> IO () draws a graphic object in a given window prepares Hugs for graphics, runs argument and cleans up. text :: Point -> String -> Graphic openwindow :: Title -> Size -> IO Window opens a window with given title and size and returns it 4 produces a graphic that consists of the given string printed at given coordinates. Point specifies top-left corner 5
11 Size and Point are types defined as follows Graphic Library Overview type Size (Int,Int) type Point (Int,Int) getkey :: Window -> IO Char width and height x and y-coordinates waits for user to press and release a key and returns corresponding character closewindow :: Window -> IO () closes given window 6 Window: draw in it a Graphic, check for Events. Graphic: built by drawing figures or text: line, polygon, polyline, ellipse, arc or text. Graphics can be stacked with overgraphic. Graphic modifiers to change Color, Pen, Brush, Font, background. Event handling: events are Char, Key, MouseMove, Button (of mouse). 7 Overview (cont d) Windows Event handling explicit and no Listeners as in Java. No complex container objects as in Java API. For more detailed information consult "The Hugs Graphics Library" document on the course webpage. Do not forget to import GraphicsUtils before use. openwindow :: Title -> Size -> IO Window closewindow :: Window -> IO () clearwindow :: Window -> IO () getgraphic :: Window -> IO Graphic setgraphic :: Window -> Graphic -> IO () drawinwindow :: Window -> Graphic -> IO () open, close, and clearwindow do the obvious. getgraphic returns the graphic of a window and setgraphic prints a graphic (overriding). drawinwindow prints over the given graphic. 8 9 Windows (cont d) Atomic Graphics getwindowrect :: Window -> IO (Point,Point) text :: Point -> String -> Graphic gets window parameters: location and size as points. Useful when the window has been resized or moved. draws a given string at a given point polygon :: [Point] -> Graphic getwindowevent :: Window -> IO Event gets next window event draws a filled polygon through points in list line :: Point -> Point -> Graphic draws a line between two points 0 2
12 Atomic Graphics arc :: Point -> Point -> Angle -> Angle -> Graphic draws an unfilled elliptical arc in rectangle defined by two points with two angles (in degrees) as shown beneath: angle2 ellipse :: Point -> Point -> Graphic angle draws a filled ellipse inside given rectangle Graphics & Modifiers overgraphic :: Graphic -> Graphic -> Graphic puts first graphic on top of second withcolor :: Color -> Graphic -> Graphic produces that graphic in given colour withtextalignment :: Alignment -> Graphic -> Graphic produces text in graphic in given alignment 2 3 Modifier Types type Color Black Blue Green Cyan Red Magenta Yellow White Colour names type Alignment (HAlign,VAlign) type HAlign Left Center Right type VAlign Top Baseline Bottom Alignment names. Default (Left,Top) Example hw :: IO () hw rungraphics ( do w <- openwindow "Hello World Window" (300,300) drawinwindow w (text (00,00) "Hello") drawinwindow w (withcolor Blue (text (00,200) "World")) drawinwindow w (withcolor Magenta (polygon [(00,60),(70,50),(00,20)])) getkey w closewindow w ) 4 5 Example Comments Hello World with World in blue Magenta polygon with three nodes triangle Events: how to get them In a nonterminating loop trace all events in a window and print them on the screen: tracer:: IO () tracer rungraphics ( do w <- openwindow "Event Tracer" (300,300) loop w ) where loop w do e <- getwindowevent w putstrln (show e) loop w 6 7 3
13 Close the window by using the window menu or typing <ALT><F4>. show also works for events and transforms them into strings. Event types data Event Char Char Key Key Bool Button Point Bool Bool MouseMove Point Resize Closed Meaning Character pressed key pressed mouse button pressed mouse moved to point window resized window closed We can mix graphic actions with our old IO actions as they are both of type IO a. Boolean parameters: Key : is key down? (or released) Button: is left (or right) mouse button pressed? is button down? (or released) 8 9 Key Event types Note that types and constructors may have the same name (Char, Key) Special keys can be checked using predicates like: isdeletekey :: Key -> Bool isescapekey :: Key -> Bool isshiftlkey :: Key -> Bool isshiftrkey :: Key -> Bool iscontrollkey :: Key -> Bool iscontrolrkey :: Key -> Bool and so on. Event Example A simple program that prints red crosses (Xs) where you move the mouse. If a character key is hit the character is printed in yellow in the middle of the window. Hitting the Escape-key closes the window crazy :: IO () crazy rungraphics ( do w <- openwindow "Move Mouse" (300,300) loop w ) loop :: Window -> IO () loop w do e <- getwindowevent w handleevent w e Open the window and start the event loop. The handler is a separate function (could be made local using where). Events: can you handle them? handleevent :: Window -> Event -> IO () handleevent w (MouseMove (x,y)) do drawinwindow w (withcolor Red (text (x,y) "X")) loop w handleevent w (Char c) do drawinwindow w (withcolor Black (polygon [(50,50),(50,70), (70,70),(70,50)] )) drawinwindow w (withcolor Yellow (text (50,50) [c])) loop w
14 handleevent w (Key a True) if isescapekey a then closewindow w else loop w handleevent w _ loop Pattern matching can be used for Event argument in an event handler definition. Deletion of text is done by drawing a rectangle in background colour. One has to catch also the events one is not interested in or the program will abort. Exercises () (2) Write a program that opens a window (of appropriate size) and draws a red square of length 00 pixels and a blue circle of radius 50 pixels next to each other. Swap the colours of the graphics when a mouse button has been pressed and close the window when the left Shift key has been pressed (3) Write a program that opens a window, waits for the user to type printable characters on the keyboard and echoes them in the window (as long as there is space). If the left mouse button is pressed the content of the window is erased and printing starts again in the top left corner. The right button closes the window. Assume that characters have width 9 pixels and height 4 pixels. 26 5
15 FUNCTIONAL PROGRAMMING Modules!For bigger projects Haskell scripts should be structured and split into modules.!a module consists of type, function, and object definitions with a clearly defined interface. Bernhard Reus Lecture 2 - Modules!Interfaces state what is exported and what is imported. Advantages of Modules!separate development!separate compilation!re-usability (libraries)!reduce complexity Module Headers Syntax for module is as follows: module <Name> where <list of definitions>! <Name> must start with an uppercase letter and is the module s name. The file itself must be called <Name>.hs.!The <list of definitions> contains definitions in the usual way. They describe the entities defined in the module. For example, consider a file Gui.hs: module Gui where type Point (Int,Int) movepoint:: Point -> Int -> Point movepoint (x,y) z (x+z,y+z) After loading Gui.hs Hugs will change its prompt indicating that evaluation now is w.r.t. the definitions in module Gui. Gui> Import The import clause allows one to import other modules definitions: module Gui where import GraphicsUtils import MyOtherModule data Shape Rect Point Point Circle Int drawshape:: Window -> Shape -> Graphic drawshape w (Rect p p2) drawshape w (Circle n)
16 Import Caveats Export Controls!Obey layout rule with respect to import keyword.!by default a module exports all the definitions it contains but not the imported ones.!avoid cyclic imports.!this can be changed by explicitly providing an export list:!make sure that the.hs file containing your module has the right name (that is the same name). module Gui (Shape (..),drawshape) where import GraphicsUtils data Shape drawshape ::!The export list contains the names of the exported objects and types. The list is written in parentheses and names are separated by commas.!therefore, the following two definitions are equivalent: module Gui (module Gui) where! Shape (..) indicates that the type Shape with its constructors is exported. module Gui where!other example:!to export a whole module write: module Gui (module GraphicsUtils) where module Gui (module Gui, module Prelude) where Name Clashes Import Controls!If files are imported then there is always the danger of name clashes. For example,!like export lists one can also define import lists explicitly. For example: module A where import B f x x + 3 module B where f xs foo ++ xs g map f module A where import B (g) f x x + 3 module B where f xs foo ++ xs g map f!to avoid name clashes one can control the import list:!only the names in the list (in parentheses, separated by commas) are imported.!in the definition of g, f still refers to the f of B. 2
17 Shadowing!Hiding names that can be used for other definitions is also called shadowing.!keyword hiding allows one to shadow several names and import all the rest: module A where import B hiding (f) f x x + 3!Again, the list of names can contain types and names are separated by commas. Qualified Names!What if one likes to use both functions named f in modules A and B? How can the name clash be resolved then?!use qualified names.!a qualified name is built from the name of a module and the name of an object in that module. For example: A.f B.f Qualified Import!Use keyword qualified to make imported names qualified. For example: module A where import qualified B f x x +3 g map B.f!Qualified import can be combined with all the other features of import lists.!in export lists there must not be any name clashes.!attention: A qualifier in a name identifies the module an entity is imported from, not the module it is defined in. For example: module A (B.f, C.f) where import qualified B(f) import qualified C(f)!Name clash if one imports from A as B.f and C.f are both referenced outside A as A.f (not A.B.f and A.C.f).!Modules must be closed. Any name mentioned in the module must be defined in the source or imported from another module.!instance declarations are exported and imported automatically. Abstract Data Types!Information Hiding.!Do not give away implementation details to users of your module.!example: Sets. If there is an implementation of sets by lists how can that implementation be hidden? 3
18 Abstract Data Type Set!Use the export mechanism to hide information: module Set (Set,empty,single,union,meet) where data Set a S [a] empty S [] single x S [x] union (S xs)(s ys) S (elimdoubles (xs++ys)) meet (S xs)(s ys) S (elimdoubles [x x <- xs, elem x ys])!note that the constructor S for type Set is not exported.!therefore, the only way to construct sets in another module is by using exported functions empty, single, union, and meet.!modules that provide the same export list are interchangeable (if the types of the entities match)!no implements like in Java. How to use Modules!Modules should implement one specific task only and completely. Exercises () Put your solutions of previous exercise sheets in modules.!modules should be small.!modules should be as general as possible to support re-usability.!modules should only export what is absolutely necessary (information hiding). (2) Complete the module Set giving a definition for elimdoubles and write another module MySet that provides all the set functions where union is changed to have three arguments. All those functions but the binary union should be exported. Import them in a module C where you define some sets using union and single. (3) Write an abstract data type Stack that uses lists as data representation, Implement the following stack operations: emptys:: Stack a push :: a -> Stack a -> Stack a pop :: Stack a -> Stack a 4
19 FUNCTIONAL PROGRAMMING Type Classes Type classes are a means for defining overloading in a clear and structured way. Type classes appear as constraints in types of overloaded functions. Bernhard Reus Lecture 3 - Classes Several type classes are built-in, for example: Ord, Eq, Num. This lecture explains how user-defined classes can be done and how they work. Overloaded Functions () :: Eq a > a -> a -> Bool (<) :: Ord a > a -> a -> Bool (+) :: Num a > a -> a -> a show :: Show a > a -> String Class constraint Different implementations of overloaded functions provided in different types. Class & Instance A class is the collection of types over which an overloaded function is defined. The members (types) of a class are called instances. For example, instances of Eq are: Int, Bool, String, Float, but also (Int,Char), [Char], [[Char]], [(Char,Char)], and so on. Thus, () works for all instances of Eq. 2 3 How to Define a Class How to Define an Instance class <Name> <TypeVar> where <signature involving <TypeVar>> A signature is a list of function names with their types. To write down these types, a type variable is used that represents the possible instances. For example: class Eq a where () :: a -> a -> Bool 4 instance <ClassName> <Type> where <definition of functions in the signature of <ClassName>> The definitions of the functions refer now to the specified type that replaces the type variable in the class definition. Example: instance Eq Bool where True True True True False False False True False False False True 5
20 For built-in numeric types like Float and Int etc., instance definitions refer to appropriate primitive equality definitions provided as native code by the compiler. For user defined classes functions are defined as usual (using pattern matching etc.). Default Implementations class Eq a where (), (/) :: a -> a -> Bool x. / y not (x y) Classes can contain default implementations. Classes can depend on other classes and instances can depend on other instances. Default implementations can be overridden by instance definitions. 6 7 Derived Classes Class definitions may depend on other classes. For example: class Eq a > Ord a where (<),(<),(>),(>) :: a -> a -> Bool This means that an instance of Ord must not only provide the functions of Ord s signature but also of Eq s signature. The functions of Eq can then be used to implement the functions of Ord. Ord is inheriting operations from Eq. max, min :: a -> a -> a 8 9 Type a cannot appear in a (class) context not mentioned in the instance declaration. class Eq a > ShowEq a where ifs :: Show a > a -> a -> String foo :: Show b > b -> (String,a) class (Eq a,show a) > ShowEq a where ifs :: a -> a -> String foo :: Show b > b -> (String,a) Multiple Inheritance class (Eq a,show a) > ShowEq a where ifs :: a -> a -> String ifs x y if xy then tie else show x Here the operation () from Eq and show form Show have been inherited. Several contexts can be used (more than two). 0 2
21 Derived Instances Compound types may be instances of classes if constituent types are instances of the same class. For example: instance Eq a > Eq [a] where [] [] True (x:xs) (y:ys) xy && (xsys) So the equality on a list depends on the equality on the elements of the list. Similar for tuple types. Also here multiple constraints may appear. For example: instance (Eq a, Eq b) > Eq (a,b) where (x,y) (x2,y2) xx2 && yy2 equality of type a 2 3 Data Types as Class Instances For data types there is a special syntax to declare them as instances of a certain class: data Tree a Leaf a Node (Tree a) a (Tree a) deriving (Eq,Ord,Show,Read) list of classes the type is an instance of Tree is an instance of classes Eq, Ord, Show, and Read. Keyword deriving indicates the following implicit instance declarations. You can only use the following classes: Eq, Ord, Show, Enum, Read as for others the instances cannot be computed automatically. Ord defines a lexicographic ordering on the data type. 4 5 Constructors are ordered by order of appearance. For example (Leaf 30) < (Node (Leaf ) (Leaf 2)) (Leaf 3) < (Leaf ) Class Show allows usage of function show : a -> String which converts a value into a string. > show (Node (Leaf ) (Leaf 2)) Node (Leaf ) (Leaf 2) Read is the opposite of Show and allows one to parse values of the given type from a string. The function it provides is: read :: Read a > String -> a This parser works for all values of Haskell types in Haskell syntax. Note that the string must be completely consumed by the parser
22 Examples for Read > read > head (read [,2] ) > read 34xx + 3 Program error Prelude. read no parse Enumeration Types If all constructors are nullary then this defines an enumeration type and one can declare it to be an instance of class Enum. For example: data Car Ford Jag Merc Porsche deriving (Show,Read,Ord,Eq,Enum) declares an enumeration type space important here > [Jag.. ] [Jag,Merc,Porsche] 8 9 Higher-Order Classes Classes can not only be defined on types, but also on type constructors. Type constructors are for example: (->), [], (,), (,,) function space, lists, tuples, triples etc. An example is the monad class Monad a. One can declare an instance of the list monad like this: instance Monad [] where return t [t] xs >> f concat (map f xs) This is already done in Prelude. One can not declare a type alias defined via type N a as instance of a class Comparison with OOP In Haskell and OOP classes capture a common set of operations. In both cases we have instances, inheritance, default implementations and overriding. Kinds of Polymorphism Subtype polymorphism in OOP. Which operation is called depends on dynamic type of object. Generic (parametric) polymorphism in Haskell combined with overloading in a neat way. Type classes provide smaller universes of types. In Haskell instances are types that have no mutable state. Correspondingly, it can be computed at compile time which overloaded operation is used. f :: a -> Bool possible instances of a: all types 22 f :: C a > a -> Bool all types in class C 23 4
23 FUNCTIONAL PROGRAMMING Lazy Evaluation denotes a certain evaluation strategy that only evaluates an expression when the result is needed. allows for infinite data structures. Bernhard Reus supports a more abstract programming style Lecture 4 - Lazy Evaluation Most other languages are eager. Lazy Function Application Recall the boolean operator (&&) that only evaluates its second argument if the first one was True. One can test whether an argument of a function is evaluated by applying the function to undefined: > False && undefined False > undefined && True Program error: {undefined} Arguments of functions are evaluated by need. If an argument has to be evaluated, however, then it is evaluated just once. For example in f x y x + x + x >f (2+3) (2^2) 5 (2+3) is evaluated only once and (2^2) never. 2 3 Lazy Data Structures If a structured element like * a tuple (s,t) * a list x:xs * a value of a datatype C(t, tn) is evaluated then only those parts are evaluated that are really needed. For example, in > head (:undefined) the argument list is only evaluated until its head element is known. Infinite Data Structures Since evaluation is lazy, values of data types can be infinite by recursion. For example, this recursive definition of a list xs :: [Int] xs :xs defines an infinite list of s. > xs [,,,,,,,^C {Interrupted} 4 5
24 Evaluation of > xs yields xs :xs :(:xs) :(:(:xs)) [,,,,,,,,, 6 Evaluation of > take 2 xs yields take 2 xs take 2 (:xs) :(take xs) :(take (:xs)) ::(take 0 xs) ::[] [,] 7 Sieve of Eratosthenes This algorithm, over 2000 years old, computes the list of prime numbers Idea: Start with a list of all numbers but Once a prime number is found cancel out all its multiples Sieve Algorithm Start with a list of all numbers but. The head of the list is a prime number. Cancel out all multiples of the head in the rest list. Repeat that algorithm for the new rest list. sieve :: [Int] -> [Int] sieve (x:xs) x:(sieve [y y <- xs, y `mod` x > 0]) prime :: [Int] prime sieve [2..] 0 Evaluation of yields prime sieve [2..] 2:(sieve [y y<-[3..], y`mod`2 > 0]) 2:(sieve (3:[y y<-[4..], y`mod`2 > 0])) 2:3:(sieve [z z<-[y y<-[4..],y`mod`2>0], z `mod` 3 > 0 ]) prime 2
25 prime can be used to check primality but be careful: > elem prime 7 True > elem prime 6 no reply! Not to be in prime takes an infinite number of tests to check. Do we really have to test for all numbers in the list? No. Use the fact that the list is ordered: elemord:: Ord a > [a] -> a -> Bool elemord (x:xs) y x < y elemord xs y x y True otherwise False >elemord prime 6 False 2 3 Process Networks In Haskell not only lists but any data structure is implicitly infinite. But infinite lists are particularly interesting. input a 0,a,a 2, A Sample Network a i + b i b,b 2,b 3, They model data streams in networks where input and output are streams. Streams are manipulated by stream processing operations. 4 0,b,b 2,b 3 (0:) feedback result 5 This process network can be expressed using infinite lists and recursion. For example: network as plus as (0:(network as)) where plus xs ys map (\(x,y)-> x+y) (zip xs ys) What does this compute? >take 5 (network [..]) [0,,3,6,0] Rabbit Reproduction In an ideal rabbit world rabbits reproduce at the age of 2 months and from then on produce a new couple of rabbits every month. If you start with one newborn couple, how many couples do you have after n months if no rabbits die (it s an ideal world after all)? b n a 0 + a + a a n
26 How many rabbit couples are there? Months couples 0 Building principle: rabbits(n+2) rabbits(n+) + rabbits(n) old rabbits new rabbits These numbers are called Fibonacci numbers. They occur often in nature (for example the number of florets in sunflowers etc. ). rabbits(n+)/rabbits(n) converges to the golden ratio. 9 Network for Fibonacci,b 2,b 3,b 4, feedback + b 2,b 3,b 4, Implementation of the Fibonacci network using infinite lists: fib ::(plus fib (tail fib)) where plus xs ys map (\(x,y) -> x+y)(zip xs ys) tail,,b 2,b 3,b 4, (::) > take 7 fib [,,2,3,5,8,3] output 20 2 Advantages of Infinite Lists Exercises Abstraction: programs can be designed without care about the possible length of the lists. () Write a process network that merges two given input streams of numbers that are supposed to be ordered. Stream-based (process-based) programming of networks. Feedback by recursion. (2) Write mergesort as a process network. Can it work for infinite lists? Making use of higher-order functions one can develop a library of network components that can be composed. 22 (3) Define a process network that computes the output stream of Hamming numbers in ascending order. The Hamming numbers are all the numbers which have prime factors in [2, 3, 5]. 23 4
Programming Language Rankings. Lecture 15: Type Inference, polymorphism & Type Classes. Top Combined. Tiobe Index. CSC 131! Fall, 2014!
Programming Language Rankings Lecture 15: Type Inference, polymorphism & Type Classes CSC 131 Fall, 2014 Kim Bruce Top Combined Tiobe Index 1. JavaScript (+1) 2. Java (-1) 3. PHP 4. C# (+2) 5. Python (-1)
Java 6 'th. Concepts INTERNATIONAL STUDENT VERSION. edition
Java 6 'th edition Concepts INTERNATIONAL STUDENT VERSION CONTENTS PREFACE vii SPECIAL FEATURES xxviii chapter i INTRODUCTION 1 1.1 What Is Programming? 2 J.2 The Anatomy of a Computer 3 1.3 Translating
Computing Concepts with Java Essentials
2008 AGI-Information Management Consultants May be used for personal purporses only or by libraries associated to dandelon.com network. Computing Concepts with Java Essentials 3rd Edition Cay Horstmann
KITES TECHNOLOGY COURSE MODULE (C, C++, DS)
KITES TECHNOLOGY 360 Degree Solution www.kitestechnology.com/academy.php [email protected] [email protected] Contact: - 8961334776 9433759247 9830639522.NET JAVA WEB DESIGN PHP SQL, PL/SQL
Java (12 Weeks) Introduction to Java Programming Language
Java (12 Weeks) Topic Lecture No. Introduction to Java Programming Language 1 An Introduction to Java o Java as a Programming Platform, The Java "White Paper" Buzzwords, Java and the Internet, A Short
Part 1 Foundations of object orientation
OFWJ_C01.QXD 2/3/06 2:14 pm Page 1 Part 1 Foundations of object orientation OFWJ_C01.QXD 2/3/06 2:14 pm Page 2 1 OFWJ_C01.QXD 2/3/06 2:14 pm Page 3 CHAPTER 1 Objects and classes Main concepts discussed
CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards
CompuScholar, Inc. Alignment to Utah's Computer Programming II Standards Course Title: TeenCoder: Java Programming Course ISBN: 978 0 9887070 2 3 Course Year: 2015 Note: Citation(s) listed may represent
Functional Programming
FP 2005 1.1 3 Functional Programming WOLFRAM KAHL [email protected] Department of Computing and Software McMaster University FP 2005 1.2 4 What Kinds of Programming Languages are There? Imperative telling
Anatomy of Programming Languages. William R. Cook
Anatomy of Programming Languages William R. Cook Copyright (C) 2013 2 Chapter 1 Preliminaries Preface What? This document is a series of notes about programming languages, originally written for students
Fundamentals of Java Programming
Fundamentals of Java Programming This document is exclusive property of Cisco Systems, Inc. Permission is granted to print and copy this document for non-commercial distribution and exclusive use by instructors
Glossary of Object Oriented Terms
Appendix E Glossary of Object Oriented Terms abstract class: A class primarily intended to define an instance, but can not be instantiated without additional methods. abstract data type: An abstraction
Adobe Illustrator CS5 Part 1: Introduction to Illustrator
CALIFORNIA STATE UNIVERSITY, LOS ANGELES INFORMATION TECHNOLOGY SERVICES Adobe Illustrator CS5 Part 1: Introduction to Illustrator Summer 2011, Version 1.0 Table of Contents Introduction...2 Downloading
Moving from CS 61A Scheme to CS 61B Java
Moving from CS 61A Scheme to CS 61B Java Introduction Java is an object-oriented language. This document describes some of the differences between object-oriented programming in Scheme (which we hope you
core. Volume I - Fundamentals Seventh Edition Sun Microsystems Press A Prentice Hall Title ULB Darmstadt
core. 2008 AGI-Information Management Consultants May be used for personal purporses only or by libraries associated to dandelon.com network. Volume I - Fundamentals Seventh Edition CAY S. HORSTMANN GARY
An Incomplete C++ Primer. University of Wyoming MA 5310
An Incomplete C++ Primer University of Wyoming MA 5310 Professor Craig C. Douglas http://www.mgnet.org/~douglas/classes/na-sc/notes/c++primer.pdf C++ is a legacy programming language, as is other languages
History OOP languages Year Language 1967 Simula-67 1983 Smalltalk
History OOP languages Intro 1 Year Language reported dates vary for some languages... design Vs delievered 1957 Fortran High level programming language 1958 Lisp 1959 Cobol 1960 Algol Structured Programming
MyOra 3.0. User Guide. SQL Tool for Oracle. Jayam Systems, LLC
MyOra 3.0 SQL Tool for Oracle User Guide Jayam Systems, LLC Contents Features... 4 Connecting to the Database... 5 Login... 5 Login History... 6 Connection Indicator... 6 Closing the Connection... 7 SQL
ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology)
ALLIED PAPER : DISCRETE MATHEMATICS (for B.Sc. Computer Technology & B.Sc. Multimedia and Web Technology) Subject Description: This subject deals with discrete structures like set theory, mathematical
Visualization of 2D Domains
Visualization of 2D Domains This part of the visualization package is intended to supply a simple graphical interface for 2- dimensional finite element data structures. Furthermore, it is used as the low
Type Classes with Functional Dependencies
Appears in Proceedings of the 9th European Symposium on Programming, ESOP 2000, Berlin, Germany, March 2000, Springer-Verlag LNCS 1782. Type Classes with Functional Dependencies Mark P. Jones Department
Specialized Programme on Web Application Development using Open Source Tools
Specialized Programme on Web Application Development using Open Source Tools A. NAME OF INSTITUTE Centre For Development of Advanced Computing B. NAME/TITLE OF THE COURSE C. COURSE DATES WITH DURATION
PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?
1. Distinguish & and && operators. PART-A Questions 2. How does an enumerated statement differ from a typedef statement? 3. What are the various members of a class? 4. Who can access the protected members
C++ INTERVIEW QUESTIONS
C++ INTERVIEW QUESTIONS http://www.tutorialspoint.com/cplusplus/cpp_interview_questions.htm Copyright tutorialspoint.com Dear readers, these C++ Interview Questions have been designed specially to get
Chapter 6: Programming Languages
Chapter 6: Programming Languages Computer Science: An Overview Eleventh Edition by J. Glenn Brookshear Copyright 2012 Pearson Education, Inc. Chapter 6: Programming Languages 6.1 Historical Perspective
Introduction to Python
Caltech/LEAD Summer 2012 Computer Science Lecture 2: July 10, 2012 Introduction to Python The Python shell Outline Python as a calculator Arithmetic expressions Operator precedence Variables and assignment
How to build text and objects in the Titler
How to build text and objects in the Titler You can use the Titler in Adobe Premiere Pro to create text and geometric objects. There are three methods for creating text, each capable of producing either
YouthQuest Quick Key FOB Project
YouthQuest Quick Key FOB Project This project is designed to demonstrate how to use the 3D design application, Moment of inspiration, to create a custom key fob for printing on the Cube3 3D printer. Downloading
The Technology Behind a Graphical User Interface for an Equational Reasoning Assistant
The Technology Behind a Graphical User Interface for an Equational Reasoning Assistant Andy Gill Department of Computing Science, University of Glasgow Abstract The Haskell Equational Reasoning Assistant
Chapter 15 Functional Programming Languages
Chapter 15 Functional Programming Languages Introduction - The design of the imperative languages is based directly on the von Neumann architecture Efficiency (at least at first) is the primary concern,
PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON
PROBLEM SOLVING WITH SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON Addison Wesley Boston San Francisco New York London
Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months
Specialized Android APP Development Program with Java (SAADPJ) Duration 2 months Our program is a practical knowledge oriented program aimed at making innovative and attractive applications for mobile
Java Application Developer Certificate Program Competencies
Java Application Developer Certificate Program Competencies After completing the following units, you will be able to: Basic Programming Logic Explain the steps involved in the program development cycle
El Dorado Union High School District Educational Services
El Dorado Union High School District Course of Study Information Page Course Title: ACE Computer Programming II (#495) Rationale: A continuum of courses, including advanced classes in technology is needed.
Lab 7 Keyboard Event Handling Mouse Event Handling
Lab 7 Keyboard Event Handling Mouse Event Handling Keyboard Event Handling This section explains how to handle key events. Key events are generated when keys on the keyboard are pressed and released. These
UNIVERSITY OF LONDON (University College London) M.Sc. DEGREE 1998 COMPUTER SCIENCE D16: FUNCTIONAL PROGRAMMING. Answer THREE Questions.
UNIVERSITY OF LONDON (University College London) M.Sc. DEGREE 1998 COMPUTER SCIENCE D16: FUNCTIONAL PROGRAMMING Answer THREE Questions. The Use of Electronic Calculators: is NOT Permitted. -1- Answer Question
Understand the Sketcher workbench of CATIA V5.
Chapter 1 Drawing Sketches in Learning Objectives the Sketcher Workbench-I After completing this chapter you will be able to: Understand the Sketcher workbench of CATIA V5. Start a new file in the Part
Intro to Excel spreadsheets
Intro to Excel spreadsheets What are the objectives of this document? The objectives of document are: 1. Familiarize you with what a spreadsheet is, how it works, and what its capabilities are; 2. Using
Specialized Programme on Web Application Development using Open Source Tools
Specialized Programme on Web Application Development using Open Source Tools Objective: At the end of the course, Students will be able to: Understand various open source tools(programming tools and databases)
DIA Creating Charts and Diagrams
DIA Creating Charts and Diagrams Dia is a vector-based drawing tool similar to Win32 OS Visio. It is suitable for graphical languages such as dataflow diagrams, entity-relationship diagrams, organization
Working With Animation: Introduction to Flash
Working With Animation: Introduction to Flash With Adobe Flash, you can create artwork and animations that add motion and visual interest to your Web pages. Flash movies can be interactive users can click
Getting Started with Excel 2008. Table of Contents
Table of Contents Elements of An Excel Document... 2 Resizing and Hiding Columns and Rows... 3 Using Panes to Create Spreadsheet Headers... 3 Using the AutoFill Command... 4 Using AutoFill for Sequences...
Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science. Unit of Study / Textbook Correlation
Thomas Jefferson High School for Science and Technology Program of Studies Foundations of Computer Science updated 03/08/2012 Unit 1: JKarel 8 weeks http://www.fcps.edu/is/pos/documents/hs/compsci.htm
Moderator Guide. o m N o v i a T e c h n o l o g i e s 8 5 8 8 K a t y F r e e w a y H o u s t o n, T X 7 7 0 2 4 + 1 2 8 1-5 0 0-4 0 6 5
Moderator Guide o m N o v i a T e c h n o l o g i e s 8 5 8 8 K a t y F r e e w a y H o u s t o n, T X 7 7 0 2 4 + 1 2 8 1-5 0 0-4 0 6 5 TABLE OF CONTENTS Room Access -------------------------------------------------------------------------------------------------------------
Timber: A Programming Language for Real-Time Embedded Systems
Timber: A Programming Language for Real-Time Embedded Systems Andrew P. Black, Magnus Carlsson, Mark P. Jones, Richard Kieburtz and Johan Nordlander Department of Computer Science and Engineering OGI School
Hypercosm. Studio. www.hypercosm.com
Hypercosm Studio www.hypercosm.com Hypercosm Studio Guide 3 Revision: November 2005 Copyright 2005 Hypercosm LLC All rights reserved. Hypercosm, OMAR, Hypercosm 3D Player, and Hypercosm Studio are trademarks
Object-Oriented Databases
Object-Oriented Databases based on Fundamentals of Database Systems Elmasri and Navathe Acknowledgement: Fariborz Farahmand Minor corrections/modifications made by H. Hakimzadeh, 2005 1 Outline Overview
Compiler Construction
Compiler Construction Lecture 1 - An Overview 2003 Robert M. Siegfried All rights reserved A few basic definitions Translate - v, a.to turn into one s own language or another. b. to transform or turn from
Creating Hyperlinks & Buttons InDesign CS6
Creating Hyperlinks & Buttons Adobe DPS, InDesign CS6 1 Creating Hyperlinks & Buttons InDesign CS6 Hyperlinks panel overview You can create hyperlinks so that when you export to Adobe PDF or SWF in InDesign,
Syllabus for CS 134 Java Programming
- Java Programming Syllabus Page 1 Syllabus for CS 134 Java Programming Computer Science Course Catalog 2000-2001: This course is an introduction to objectoriented programming using the Java language.
Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick Reference Guide
Open Crystal Reports From the Windows Start menu choose Programs and then Crystal Reports. Creating a Blank Report Ohio University Computer Services Center August, 2002 Crystal Reports Introduction Quick
Functional Programming. Functional Programming Languages. Chapter 14. Introduction
Functional Programming Languages Chapter 14 Introduction Functional programming paradigm History Features and concepts Examples: Lisp ML 1 2 Functional Programming Functional Programming Languages The
Randy Hyde s Win32 Assembly Language Tutorials (Featuring HOWL) #4: Radio Buttons
Randy Hyde s Win32 Assembly Language Tutorials Featuring HOWL #4: Radio Buttons In this fourth tutorial of this series, we ll take a look at implementing radio buttons on HOWL forms. Specifically, we ll
Portal Connector Fields and Widgets Technical Documentation
Portal Connector Fields and Widgets Technical Documentation 1 Form Fields 1.1 Content 1.1.1 CRM Form Configuration The CRM Form Configuration manages all the fields on the form and defines how the fields
Java the UML Way: Integrating Object-Oriented Design and Programming
Java the UML Way: Integrating Object-Oriented Design and Programming by Else Lervik and Vegard B. Havdal ISBN 0-470-84386-1 John Wiley & Sons, Ltd. Table of Contents Preface xi 1 Introduction 1 1.1 Preliminaries
Interaction: Mouse and Keyboard DECO1012
Interaction: Mouse and Keyboard DECO1012 Interaction Design Interaction Design is the research and development of the ways that humans and computers interact. It includes the research and development of
09336863931 : provid.ir
provid.ir 09336863931 : NET Architecture Core CSharp o Variable o Variable Scope o Type Inference o Namespaces o Preprocessor Directives Statements and Flow of Execution o If Statement o Switch Statement
GFI FAXmaker 14 for Exchange/Lotus/SMTP. Fax-Client Manual. By GFI Software Ltd
GFI FAXmaker 14 for Exchange/Lotus/SMTP Fax-Client Manual By GFI Software Ltd http://www.gfi.com Email: [email protected] Information in this document is subject to change without notice. Companies, names,
Testing and Tracing Lazy Functional Programs using QuickCheck and Hat
Testing and Tracing Lazy Functional Programs using QuickCheck and Hat Koen Claessen 1, Colin Runciman 2, Olaf Chitil 2, John Hughes 1, and Malcolm Wallace 2 1 Chalmers University of Technology, Sweden
The Clean programming language. Group 25, Jingui Li, Daren Tuzi
The Clean programming language Group 25, Jingui Li, Daren Tuzi The Clean programming language Overview The Clean programming language first appeared in 1987 and is still being further developed. It was
Plotting: Customizing the Graph
Plotting: Customizing the Graph Data Plots: General Tips Making a Data Plot Active Within a graph layer, only one data plot can be active. A data plot must be set active before you can use the Data Selector
Grandstream XML Application Guide Three XML Applications
Grandstream XML Application Guide Three XML Applications PART A Application Explanations PART B XML Syntax, Technical Detail, File Examples Grandstream XML Application Guide - PART A Three XML Applications
Regular Expressions and Automata using Haskell
Regular Expressions and Automata using Haskell Simon Thompson Computing Laboratory University of Kent at Canterbury January 2000 Contents 1 Introduction 2 2 Regular Expressions 2 3 Matching regular expressions
Programming and Reasoning with Side-Effects in IDRIS
Programming and Reasoning with Side-Effects in IDRIS Edwin Brady 19th October 2014 Contents 1 Introduction 3 1.1 Hello world............................................. 3 1.2 Outline................................................
Google Docs Basics Website: http://etc.usf.edu/te/
Website: http://etc.usf.edu/te/ Google Docs is a free web-based office suite that allows you to store documents online so you can access them from any computer with an internet connection. With Google
Topics. Introduction. Java History CS 146. Introduction to Programming and Algorithms Module 1. Module Objectives
Introduction to Programming and Algorithms Module 1 CS 146 Sam Houston State University Dr. Tim McGuire Module Objectives To understand: the necessity of programming, differences between hardware and software,
1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier.
Study Group 1 Variables and Types 1. Define: (a) Variable, (b) Constant, (c) Type, (d) Enumerated Type, (e) Identifier. 2. What does the byte 00100110 represent? 3. What is the purpose of the declarations
Sources: On the Web: Slides will be available on:
C programming Introduction The basics of algorithms Structure of a C code, compilation step Constant, variable type, variable scope Expression and operators: assignment, arithmetic operators, comparison,
I PUC - Computer Science. Practical s Syllabus. Contents
I PUC - Computer Science Practical s Syllabus Contents Topics 1 Overview Of a Computer 1.1 Introduction 1.2 Functional Components of a computer (Working of each unit) 1.3 Evolution Of Computers 1.4 Generations
Creating Custom Crystal Reports Tutorial
Creating Custom Crystal Reports Tutorial 020812 2012 Blackbaud, Inc. This publication, or any part thereof, may not be reproduced or transmitted in any form or by any means, electronic, or mechanical,
Introduction to Python
WEEK ONE Introduction to Python Python is such a simple language to learn that we can throw away the manual and start with an example. Traditionally, the first program to write in any programming language
MICROSOFT ACCESS STEP BY STEP GUIDE
IGCSE ICT SECTION 11 DATA MANIPULATION MICROSOFT ACCESS STEP BY STEP GUIDE Mark Nicholls ICT Lounge P a g e 1 Contents Task 35 details Page 3 Opening a new Database. Page 4 Importing.csv file into the
Fireworks CS4 Tutorial Part 1: Intro
Fireworks CS4 Tutorial Part 1: Intro This Adobe Fireworks CS4 Tutorial will help you familiarize yourself with this image editing software and help you create a layout for a website. Fireworks CS4 is the
Programming Languages in Artificial Intelligence
Programming Languages in Artificial Intelligence Günter Neumann, German Research Center for Artificial Intelligence (LT Lab, DFKI) I. AI programming languages II. Functional programming III. Functional
Object Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa October 28, 2010 G. Lipari (Scuola Superiore Sant Anna) Introduction
Python Programming: An Introduction To Computer Science
Python Programming: An Introduction To Computer Science Chapter 8 Booleans and Control Structures Python Programming, 2/e 1 Objectives æ To understand the concept of Boolean expressions and the bool data
Formal Engineering for Industrial Software Development
Shaoying Liu Formal Engineering for Industrial Software Development Using the SOFL Method With 90 Figures and 30 Tables Springer Contents Introduction 1 1.1 Software Life Cycle... 2 1.2 The Problem 4 1.3
Database Programming with PL/SQL: Learning Objectives
Database Programming with PL/SQL: Learning Objectives This course covers PL/SQL, a procedural language extension to SQL. Through an innovative project-based approach, students learn procedural logic constructs
Overview of the Adobe Flash Professional CS6 workspace
Overview of the Adobe Flash Professional CS6 workspace In this guide, you learn how to do the following: Identify the elements of the Adobe Flash Professional CS6 workspace Customize the layout of the
Computer Programming I
Computer Programming I COP 2210 Syllabus Spring Semester 2012 Instructor: Greg Shaw Office: ECS 313 (Engineering and Computer Science Bldg) Office Hours: Tuesday: 2:50 4:50, 7:45 8:30 Thursday: 2:50 4:50,
Python Lists and Loops
WEEK THREE Python Lists and Loops You ve made it to Week 3, well done! Most programs need to keep track of a list (or collection) of things (e.g. names) at one time or another, and this week we ll show
UNIVERSITY OF CALIFORNIA BERKELEY Engineering 7 Department of Civil and Environmental Engineering. Object Oriented Programming and Classes in MATLAB 1
UNIVERSITY OF CALIFORNIA BERKELEY Engineering 7 Department of Civil and Environmental Engineering Spring 2013 Professor: S. Govindjee Object Oriented Programming and Classes in MATLAB 1 1 Introduction
Domains and Competencies
Domains and Competencies DOMAIN I TECHNOLOGY APPLICATIONS CORE Standards Assessed: Computer Science 8 12 I VII Competency 001: The computer science teacher knows technology terminology and concepts; the
User Guide 14 November 2015 Copyright GMO-Z.com Forex HK Limited All rights reserved.
User Guide 14 November 2015 Copyright GMO-Z.com Forex HK Limited All rights reserved. Table of Contents Section ONE: Layout I. General View II. Quotes List III. Chart Window Section TWO: Drawing Tools
TECHNOLOGY Computer Programming II Grade: 9-12 Standard 2: Technology and Society Interaction
Standard 2: Technology and Society Interaction Technology and Ethics Analyze legal technology issues and formulate solutions and strategies that foster responsible technology usage. 1. Practice responsible
Microsoft Excel 2010 Tutorial
1 Microsoft Excel 2010 Tutorial Excel is a spreadsheet program in the Microsoft Office system. You can use Excel to create and format workbooks (a collection of spreadsheets) in order to analyze data and
MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.
Exam Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question. 1) The JDK command to compile a class in the file Test.java is A) java Test.java B) java
Single Page Web App Generator (SPWAG)
Single Page Web App Generator (SPWAG) Members Lauren Zou (ljz2112) Aftab Khan (ajk2194) Richard Chiou (rc2758) Yunhe (John) Wang (yw2439) Aditya Majumdar (am3713) Motivation In 2012, HTML5 and CSS3 took
ML for the Working Programmer
ML for the Working Programmer 2nd edition Lawrence C. Paulson University of Cambridge CAMBRIDGE UNIVERSITY PRESS CONTENTS Preface to the Second Edition Preface xiii xv 1 Standard ML 1 Functional Programming
Windows PowerShell Essentials
Windows PowerShell Essentials Windows PowerShell Essentials Edition 1.0. This ebook is provided for personal use only. Unauthorized use, reproduction and/or distribution strictly prohibited. All rights
PIC 10A. Lecture 7: Graphics II and intro to the if statement
PIC 10A Lecture 7: Graphics II and intro to the if statement Setting up a coordinate system By default the viewing window has a coordinate system already set up for you 10-10 10-10 The origin is in the
Desktop, Web and Mobile Testing Tutorials
Desktop, Web and Mobile Testing Tutorials * Windows and the Windows logo are trademarks of the Microsoft group of companies. 2 About the Tutorial With TestComplete, you can test applications of three major
Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language
Simple C++ Programs Engineering Problem Solving with C++, Etter/Ingber Chapter 2 Simple C++ Programs Program Structure Constants and Variables C++ Operators Standard Input and Output Basic Functions from
Designing a poster. Big is important. Poster is seldom linear, more like a MindMap. The subjects belonging together are located close to each other.
Designing a poster Poster is seldom linear, more like a MindMap The subjects belonging together are located close to each other. Big is important. Warm colours bring closer, cold ones estrange. A human
Chapter 1: Key Concepts of Programming and Software Engineering
Chapter 1: Key Concepts of Programming and Software Engineering Software Engineering Coding without a solution design increases debugging time - known fact! A team of programmers for a large software development
Intellect Platform - The Workflow Engine Basic HelpDesk Troubleticket System - A102
Intellect Platform - The Workflow Engine Basic HelpDesk Troubleticket System - A102 Interneer, Inc. Updated on 2/22/2012 Created by Erika Keresztyen Fahey 2 Workflow - A102 - Basic HelpDesk Ticketing System
The Needle Programming Language
The Needle Programming Language The Needle Programming Language 1 What is Needle? Needle is an object-oriented functional programming language with a multimethod-based OO system, and a static type system
ASCII Encoding. The char Type. Manipulating Characters. Manipulating Characters
The char Type ASCII Encoding The C char type stores small integers. It is usually 8 bits. char variables guaranteed to be able to hold integers 0.. +127. char variables mostly used to store characters
Object Oriented Software Design
Object Oriented Software Design Introduction to Java - II Giuseppe Lipari http://retis.sssup.it/~lipari Scuola Superiore Sant Anna Pisa September 14, 2011 G. Lipari (Scuola Superiore Sant Anna) Introduction
MyOra 3.5. User Guide. SQL Tool for Oracle. Kris Murthy
MyOra 3.5 SQL Tool for Oracle User Guide Kris Murthy Contents Features... 4 Connecting to the Database... 5 Login... 5 Login History... 6 Connection Indicator... 6 Closing the Connection... 7 SQL Editor...
