In Computer Science Computer Science, a Pointer Is a Programming

Total Page:16

File Type:pdf, Size:1020Kb

In Computer Science Computer Science, a Pointer Is a Programming InIn computercomputer science,,aa pointer is aa programmingprogramming language datadata type whosewhose value refers directly to (or "points to") another value stored elsewhere in thethe computecomputerr memory usingusing its address..ForFor high-levelhigh-level programming languages,,pointerspointers effectively take the place of of generalgeneral purpose registers inin low-level languages such asas assemblyassembly language oror machinemachine code,,butbut may be in availableavailable memorymemory..AA pointer references a location in memory, and obtaining the value at the location a pointer refers to is known as dereferencing the pointer. A pointer is a simple, more concrete implementation of the more ababstract stract reference datadata type. Several languages support some type of pointer, although some have more restrictions on their use than others. As an analogy, a page number in a book could be considered a pointer to the corresponding pagepage;; dereferencing such a pointer would be done by fliflippingpping to the page with the given page number. Pointers to data significantly improve performance for repetitive operations such as traversingtraversing stringsstrings,, lookuplookup tables,, controlcontrol tables andand treetree structures.structures. In particular, it is often much cheaper in time and space to copy and dereferedereferencence pointers than it iiss ttoo copy and access the data to whiPointers are also used to hold the addresses of entry points forfor calledcalled subroutines inin proceduralprocedural programming andand forfor run-timerun-time linking to dynamic link libraries (DLLs)..InIn object-orientedobject-oriented programming,, pointerspointers to functions areare used forfor bindingbinding methodsmethods,, often using what are calledcalled virtualvirtual method tables.. While "pointer" has been used to refer to references in general, it more properly applies to data structures whose interface explicitly allows the pointer to be manipulated (arithmetically via pointer arithmetic) as a memory address, as opposed to aa magicmagic cookicookiee oror capabilitycapability where this is not possible.[[citation needed ]] BecausBecausee pointers allow both protected and unprotected access to memory addresses, there are risks associated with using them particularly in the latter case. Primitive pointers are often stored in a format similar to anan integerinteger;;however,however, attempting to dereference or "look up" a pointer whose value was never a valid memory address would cause a program to crash. To ameliorate this potential problem, as a matter of type safety,,pointerspointers are considered a separate type to the tytypepe of data they point to, even if the underlying representation is ch the pointers point. Use in data structures When setting upup datadata structures likelike listslists,, queuesqueues andand trees, it is necessary to have pointers to help manage how the structure is implemented and cocontrolled.ntrolled. Typical examples of pointerspointers are start pointers, end pointers, andand stack stack pointers.pointers. These pointers can either be absolute (the actualactual physicalphysical address oror aa virtualvirtual address inin virtualvirtual memory))oror relative (an(an offsetoffset fromfrom an absolute start address ("base") that typically uses fewer bits than a full address, but will usually require one additional arithmetic operation to resolve). A two-byte offset, containing a 1616-bit,-bit, unsigned ininteger,teger, can be used to provide relarelativetive addressing for up to 64 kilobytes of a data structure. This can easily be eextendedxtended to 128K, 256K or 512K if the address pointed to is forced to be on a half-word, word or double-word boundary (but, requiring an additional "shift left" bitwisebitwise operation — by 1,2 or 3 bits — inin order to adjust the offset by a factor of 2,3 or 4, before its addition to the base addresaddress).s). Generally, though, such schemes are a lot of troubltrouble,e, and for convenience to the programmer aa flat address space is preferred. A one byte offset, such as the hexadecimalhexadecimal ASCIIASCII valuevalue of a character (e.g. X'29') can be used to point to an alternative integer value (or index) in an array (e.g. X'01'). In this way, characters can be very efficiently translated from ''rawraw data'' to a usable sequentialsequential indexindex andand then to an absolute address without aa lookuplookup table.. [[editedit] Use in control tables Control tables,,thatthat are used to controlcontrol programprogram flow,,usuallyusually make extensive use of pointers. The pointers, usually embeddeembeddedd in a table entry, mamay,y, for instance, be used to hholdold the entry points toto subroutinessubroutines toto be executed, based on certain conditions defindefineded in the same table entry. The pointers can however be simply indexes ttoo other separate, but associated, tables comprising an array of the actual addresses or the addresses themselves (depending(depending upon the programming language constructs availabavailable).le). They cacann also be used to point ((back)back) to earlier table entries (as in loop processing) or forward to skip some table entries (as in aa switchswitch oror "early" exit from a loop). For this latter purpose, the "pointer" may simply be the tabletable entry number itself and can be transformed into an actual address by simple arithmetic. [[editedit] Architectural roots Pointers are a very thinthin abstractionabstraction onon top of the addressing capabilities provided by mmostost modernmodern architecturesarchitectures..InIn the simplest scheme, anan address,,oror a numericnumeric indexindex,,isis assigned to each unit of memory in the system, where the unit is typically either aa bytebyte oror aa wordword,, effectively transforming all of memory into a very largelarge arrayarray..Then,Then, if we have an address, the system provides an operation to retrieve the value stored in the memory unit at that address (usually utilizing the machine'smachine's generalgeneral purpose registers)).. In the usual case, a pointer is large enough to hold more addresses than there are units of memory in the system. This introduces the possibilipossibilityty that a program may attemattemptpt to access an address which corresponds to no unit of memory, either because not enough memory is installed (i.e. beyond the range of available memormemory)y) or the architecture does not supportsupport such addresses. The first case may, in certain platformsplatforms such as thethe IntelIntel x86 architecture,architecture, be called aa segmentationsegmentation fault (segfault).(segfault). The second case is possible in the currentcurrent implementation of of AMD64AMD64,,wherewhere pointers are 64 bit long and addresses only extendextend to 48 bits. There, pointers must conform to certain rules (canonical addresses), so if a noncannoncanonicallonica pointer is dereferenced, the processor raises aa gegeneralneral protection fault.. On the other hand, some systems have more units of memory than there are adaddresses.dresses. In this case, a more complex scheme such asas memorymemory segmentsegmentationation oror pagingpaging isis employed to use different parts of the memory at different times. The last incarnations of the x86 architecture support up to 36 bits of physical memory addresses, which were mapped to the 32-bit linear address space through thethe PAEPAE pagingpaging mechanism. Thus, only 1/16 of the possible ttotalotal memory may be accessed at a time. Another example in the same computer family was the 16-bit16-bit protectedprotected mode ofof thethe 8028680286 processor,processor, which, though supporting only 16 MiB oof f physical memory, could accesaccesss up to 1 GiB of virtual memory, but the combinatiocombinationn of 16-bit address and segment registers made accessing more than 64 KiB in one data structure cumbersome. Some restrictions of ANSI pointer arithmetic may have been due to the segmented memory models of this processor family. In order to provide a consistent interface, some ararchitectureschitectures provideprovide memory-mappedmemory-mapped I/O,, which allows some addresses to refer to units of memory while others refer toto devicedevice registers ofof other devices in the computer. There are analogousanalogous concepts such as file offsets, array indices, and remote object references that serve some of the same purposes as addresses for other types of objects. [[editedit] Uses Pointers are directly supported without restrictions in languages such asas PL/IPL/I,, CC,, C++C++,, PascalPascal,, and mostmost assemblyassembly languages..TheyThey are primarily used for constructingconstructing referencesreferences,,whichwhich in turn are fundamental to constructing nearly allall dadatata structures,,asas well as in passing data between different parts of a program. In functional programming languages that rely heavily on lilists,sts, pointers and references are managed abstractly by the language using internal constructs likelike conscons.. When dealing with arrays, the critcriticalical lookuplookup operationoperation typically involves a stage called address calculation which involves constructing a pointer to the desireddesired data element in the array. If the data elements in the array have lengths that are divisible by powers of two, tthishis arithmetic is usually much moremore efficientefficient..PaddingPadding is frequently used as a mechanism for ensuring this is the case, despite the increased mememorymory
Recommended publications
  • Technical Report TR-2020-10
    Simulation-Based Engineering Lab University of Wisconsin-Madison Technical Report TR-2020-10 CryptoEmu: An Instruction Set Emulator for Computation Over Ciphers Xiaoyang Gong and Dan Negrut December 28, 2020 Abstract Fully homomorphic encryption (FHE) allows computations over encrypted data. This technique makes privacy-preserving cloud computing a reality. Users can send their encrypted sensitive data to a cloud server, get encrypted results returned and decrypt them, without worrying about data breaches. This project report presents a homomorphic instruction set emulator, CryptoEmu, that enables fully homomorphic computation over encrypted data. The software-based instruction set emulator is built upon an open-source, state-of-the-art homomorphic encryption library that supports gate-level homomorphic evaluation. The instruction set architecture supports multiple instructions that belong to the subset of ARMv8 instruction set architecture. The instruction set emulator utilizes parallel computing techniques to emulate every functional unit for minimum latency. This project re- port includes details on design considerations, instruction set emulator architecture, and datapath and control unit implementation. We evaluated and demonstrated the instruction set emulator's performance and scalability on a 48-core workstation. Cryp- toEmu shown a significant speed up in homomorphic computation performance when compared with HELib, a state-of-the-art homomorphic encryption library. Keywords: Fully Homomorphic Encryption, Parallel Computing, Homomorphic Instruction Set, Homomorphic Processor, Computer Architecture 1 Contents 1 Introduction 3 2 Background 4 3 TFHE Library 5 4 CryptoEmu Architecture Overview 7 4.1 Data Processing . .8 4.2 Branch and Control Flow . .9 5 Data Processing Units 9 5.1 Load/Store Unit . .9 5.2 Adder .
    [Show full text]
  • The Pros of Cons: Programming with Pairs and Lists
    The Pros of cons: Programming with Pairs and Lists CS251 Programming Languages Spring 2016, Lyn Turbak Department of Computer Science Wellesley College Racket Values • booleans: #t, #f • numbers: – integers: 42, 0, -273 – raonals: 2/3, -251/17 – floang point (including scien3fic notaon): 98.6, -6.125, 3.141592653589793, 6.023e23 – complex: 3+2i, 17-23i, 4.5-1.4142i Note: some are exact, the rest are inexact. See docs. • strings: "cat", "CS251", "αβγ", "To be\nor not\nto be" • characters: #\a, #\A, #\5, #\space, #\tab, #\newline • anonymous func3ons: (lambda (a b) (+ a (* b c))) What about compound data? 5-2 cons Glues Two Values into a Pair A new kind of value: • pairs (a.k.a. cons cells): (cons v1 v2) e.g., In Racket, - (cons 17 42) type Command-\ to get λ char - (cons 3.14159 #t) - (cons "CS251" (λ (x) (* 2 x)) - (cons (cons 3 4.5) (cons #f #\a)) Can glue any number of values into a cons tree! 5-3 Box-and-pointer diagrams for cons trees (cons v1 v2) v1 v2 Conven3on: put “small” values (numbers, booleans, characters) inside a box, and draw a pointers to “large” values (func3ons, strings, pairs) outside a box. (cons (cons 17 (cons "cat" #\a)) (cons #t (λ (x) (* 2 x)))) 17 #t #\a (λ (x) (* 2 x)) "cat" 5-4 Evaluaon Rules for cons Big step seman3cs: e1 ↓ v1 e2 ↓ v2 (cons) (cons e1 e2) ↓ (cons v1 v2) Small-step seman3cs: (cons e1 e2) ⇒* (cons v1 e2); first evaluate e1 to v1 step-by-step ⇒* (cons v1 v2); then evaluate e2 to v2 step-by-step 5-5 cons evaluaon example (cons (cons (+ 1 2) (< 3 4)) (cons (> 5 6) (* 7 8))) ⇒ (cons (cons 3 (< 3 4))
    [Show full text]
  • The Use of UML for Software Requirements Expression and Management
    The Use of UML for Software Requirements Expression and Management Alex Murray Ken Clark Jet Propulsion Laboratory Jet Propulsion Laboratory California Institute of Technology California Institute of Technology Pasadena, CA 91109 Pasadena, CA 91109 818-354-0111 818-393-6258 [email protected] [email protected] Abstract— It is common practice to write English-language 1. INTRODUCTION ”shall” statements to embody detailed software requirements in aerospace software applications. This paper explores the This work is being performed as part of the engineering of use of the UML language as a replacement for the English the flight software for the Laser Ranging Interferometer (LRI) language for this purpose. Among the advantages offered by the of the Gravity Recovery and Climate Experiment (GRACE) Unified Modeling Language (UML) is a high degree of clarity Follow-On (F-O) mission. However, rather than use the real and precision in the expression of domain concepts as well as project’s model to illustrate our approach in this paper, we architecture and design. Can this quality of UML be exploited have developed a separate, ”toy” model for use here, because for the definition of software requirements? this makes it easier to avoid getting bogged down in project details, and instead to focus on the technical approach to While expressing logical behavior, interface characteristics, requirements expression and management that is the subject timeliness constraints, and other constraints on software using UML is commonly done and relatively straight-forward, achiev- of this paper. ing the additional aspects of the expression and management of software requirements that stakeholders expect, especially There is one exception to this choice: we will describe our traceability, is far less so.
    [Show full text]
  • X86 Assembly Language Syllabus for Subject: Assembly (Machine) Language
    VŠB - Technical University of Ostrava Department of Computer Science, FEECS x86 Assembly Language Syllabus for Subject: Assembly (Machine) Language Ing. Petr Olivka, Ph.D. 2021 e-mail: [email protected] http://poli.cs.vsb.cz Contents 1 Processor Intel i486 and Higher – 32-bit Mode3 1.1 Registers of i486.........................3 1.2 Addressing............................6 1.3 Assembly Language, Machine Code...............6 1.4 Data Types............................6 2 Linking Assembly and C Language Programs7 2.1 Linking C and C Module....................7 2.2 Linking C and ASM Module................... 10 2.3 Variables in Assembly Language................ 11 3 Instruction Set 14 3.1 Moving Instruction........................ 14 3.2 Logical and Bitwise Instruction................. 16 3.3 Arithmetical Instruction..................... 18 3.4 Jump Instructions........................ 20 3.5 String Instructions........................ 21 3.6 Control and Auxiliary Instructions............... 23 3.7 Multiplication and Division Instructions............ 24 4 32-bit Interfacing to C Language 25 4.1 Return Values from Functions.................. 25 4.2 Rules of Registers Usage..................... 25 4.3 Calling Function with Arguments................ 26 4.3.1 Order of Passed Arguments............... 26 4.3.2 Calling the Function and Set Register EBP...... 27 4.3.3 Access to Arguments and Local Variables....... 28 4.3.4 Return from Function, the Stack Cleanup....... 28 4.3.5 Function Example.................... 29 4.4 Typical Examples of Arguments Passed to Functions..... 30 4.5 The Example of Using String Instructions........... 34 5 AMD and Intel x86 Processors – 64-bit Mode 36 5.1 Registers.............................. 36 5.2 Addressing in 64-bit Mode.................... 37 6 64-bit Interfacing to C Language 37 6.1 Return Values..........................
    [Show full text]
  • Common Object File Format (COFF)
    Application Report SPRAAO8–April 2009 Common Object File Format ..................................................................................................................................................... ABSTRACT The assembler and link step create object files in common object file format (COFF). COFF is an implementation of an object file format of the same name that was developed by AT&T for use on UNIX-based systems. This format encourages modular programming and provides powerful and flexible methods for managing code segments and target system memory. This appendix contains technical details about the Texas Instruments COFF object file structure. Much of this information pertains to the symbolic debugging information that is produced by the C compiler. The purpose of this application note is to provide supplementary information on the internal format of COFF object files. Topic .................................................................................................. Page 1 COFF File Structure .................................................................... 2 2 File Header Structure .................................................................. 4 3 Optional File Header Format ........................................................ 5 4 Section Header Structure............................................................. 5 5 Structuring Relocation Information ............................................... 7 6 Symbol Table Structure and Content........................................... 11 SPRAAO8–April 2009
    [Show full text]
  • Bitwise Operators in C Examples
    Bitwise Operators In C Examples Alphonse misworships discommodiously. Epigastric Thorvald perishes changefully while Oliver always intercut accusatively.his anthology plumps bravely, he shown so cheerlessly. Baillie argufying her lashkar coweringly, she mass it Find the program below table which is c operators associate from star from the positive Left shift shifts each bit in its left operand to the left. Tying up some Arduino loose ends before moving on. The next example shows you how to do this. We can understand this better using the following Example. These operators move each bit either left or right a specified number of times. Amazon and the Amazon logo are trademarks of Amazon. Binary form of these values are given below. Shifting the bits of the string of bitwise operators in c examples and does not show the result of this means the truth table for making. Mommy, security and web. When integers are divided, it shifts the bits to the right. Operators are the basic concept of any programming language, subtraction, we are going to see how to use bitwise operators for counting number of trailing zeros in the binary representation of an integer? Adding a negative and positive number together never means the overflow indicates an exception! Not valid for string or complex operands. Les cookies essentiels sont absolument necessaires au bon fonctionnement du site. Like the assembly in C language, unlike other magazines, you may treat this as true. Bitwise OR operator is used to turn bits ON. To me this looks clearer as is. We will talk more about operator overloading in a future section, and the second specifies the number of bit positions by which the first operand is to be shifted.
    [Show full text]
  • Virtual Memory - Paging
    Virtual memory - Paging Johan Montelius KTH 2020 1 / 32 The process code heap (.text) data stack kernel 0x00000000 0xC0000000 0xffffffff Memory layout for a 32-bit Linux process 2 / 32 Segments - a could be solution Processes in virtual space Address translation by MMU (base and bounds) Physical memory 3 / 32 one problem Physical memory External fragmentation: free areas of free space that is hard to utilize. Solution: allocate larger segments ... internal fragmentation. 4 / 32 another problem virtual space used code We’re reserving physical memory that is not used. physical memory not used? 5 / 32 Let’s try again It’s easier to handle fixed size memory blocks. Can we map a process virtual space to a set of equal size blocks? An address is interpreted as a virtual page number (VPN) and an offset. 6 / 32 Remember the segmented MMU MMU exception no virtual addr. offset yes // < within bounds index + physical address segment table 7 / 32 The paging MMU MMU exception virtual addr. offset // VPN available ? + physical address page table 8 / 32 the MMU exception exception virtual address within bounds page available Segmentation Paging linear address physical address 9 / 32 a note on the x86 architecture The x86-32 architecture supports both segmentation and paging. A virtual address is translated to a linear address using a segmentation table. The linear address is then translated to a physical address by paging. Linux and Windows do not use use segmentation to separate code, data nor stack. The x86-64 (the 64-bit version of the x86 architecture) has dropped many features for segmentation.
    [Show full text]
  • Java for Scientific Computing, Pros and Cons
    Journal of Universal Computer Science, vol. 4, no. 1 (1998), 11-15 submitted: 25/9/97, accepted: 1/11/97, appeared: 28/1/98 Springer Pub. Co. Java for Scienti c Computing, Pros and Cons Jurgen Wol v. Gudenb erg Institut fur Informatik, Universitat Wurzburg wol @informatik.uni-wuerzburg.de Abstract: In this article we brie y discuss the advantages and disadvantages of the language Java for scienti c computing. We concentrate on Java's typ e system, investi- gate its supp ort for hierarchical and generic programming and then discuss the features of its oating-p oint arithmetic. Having found the weak p oints of the language we pro- p ose workarounds using Java itself as long as p ossible. 1 Typ e System Java distinguishes b etween primitive and reference typ es. Whereas this distinc- tion seems to b e very natural and helpful { so the primitives which comprise all standard numerical data typ es have the usual value semantics and expression concept, and the reference semantics of the others allows to avoid p ointers at all{ it also causes some problems. For the reference typ es, i.e. arrays, classes and interfaces no op erators are available or may b e de ned and expressions can only b e built by metho d calls. Several variables may simultaneously denote the same ob ject. This is certainly strange in a numerical setting, but not to avoid, since classes have to b e used to intro duce higher data typ es. On the other hand, the simple hierarchy of classes with the ro ot Object clearly b elongs to the advantages of the language.
    [Show full text]
  • A Metaobject Protocol for Fault-Tolerant CORBA Applications
    A Metaobject Protocol for Fault-Tolerant CORBA Applications Marc-Olivier Killijian*, Jean-Charles Fabre*, Juan-Carlos Ruiz-Garcia*, Shigeru Chiba** *LAAS-CNRS, 7 Avenue du Colonel Roche **Institute of Information Science and 31077 Toulouse cedex, France Electronics, University of Tsukuba, Tennodai, Tsukuba, Ibaraki 305-8573, Japan Abstract The corner stone of a fault-tolerant reflective The use of metalevel architectures for the architecture is the MOP. We thus propose a special implementation of fault-tolerant systems is today very purpose MOP to address the problems of general-purpose appealing. Nevertheless, all such fault-tolerant systems ones. We show that compile-time reflection is a good have used a general-purpose metaobject protocol (MOP) approach for developing a specialized runtime MOP. or are based on restricted reflective features of some The definition and the implementation of an object-oriented language. According to our past appropriate runtime metaobject protocol for implementing experience, we define in this paper a suitable metaobject fault tolerance into CORBA applications is the main protocol, called FT-MOP for building fault-tolerant contribution of the work reported in this paper. This systems. We explain how to realize a specialized runtime MOP, called FT-MOP (Fault Tolerance - MetaObject MOP using compile-time reflection. This MOP is CORBA Protocol), is sufficiently general to be used for other aims compliant: it enables the execution and the state evolution (mobility, adaptability, migration, security). FT-MOP of CORBA objects to be controlled and enables the fault provides a mean to attach dynamically fault tolerance tolerance metalevel to be developed as CORBA software. strategies to CORBA objects as CORBA metaobjects, enabling thus these strategies to be implemented as 1 .
    [Show full text]
  • Address Translation
    CS 152 Computer Architecture and Engineering Lecture 8 - Address Translation John Wawrzynek Electrical Engineering and Computer Sciences University of California at Berkeley http://www.eecs.berkeley.edu/~johnw http://inst.eecs.berkeley.edu/~cs152 9/27/2016 CS152, Fall 2016 CS152 Administrivia § Lab 2 due Friday § PS 2 due Tuesday § Quiz 2 next Thursday! 9/27/2016 CS152, Fall 2016 2 Last time in Lecture 7 § 3 C’s of cache misses – Compulsory, Capacity, Conflict § Write policies – Write back, write-through, write-allocate, no write allocate § Multi-level cache hierarchies reduce miss penalty – 3 levels common in modern systems (some have 4!) – Can change design tradeoffs of L1 cache if known to have L2 § Prefetching: retrieve memory data before CPU request – Prefetching can waste bandwidth and cause cache pollution – Software vs hardware prefetching § Software memory hierarchy optimizations – Loop interchange, loop fusion, cache tiling 9/27/2016 CS152, Fall 2016 3 Bare Machine Physical Physical Address Inst. Address Data Decode PC Cache D E + M Cache W Physical Memory Controller Physical Address Address Physical Address Main Memory (DRAM) § In a bare machine, the only kind of address is a physical address 9/27/2016 CS152, Fall 2016 4 Absolute Addresses EDSAC, early 50’s § Only one program ran at a time, with unrestricted access to entire machine (RAM + I/O devices) § Addresses in a program depended upon where the program was to be loaded in memory § But it was more convenient for programmers to write location-independent subroutines How
    [Show full text]
  • Lecture 12: Virtual Memory Finale and Interrupts/Exceptions 1 Review And
    EE360N: Computer Architecture Lecture #12 Department of Electical and Computer Engineering The University of Texas at Austin October 9, 2008 Disclaimer: The contents of this document are scribe notes for The University of Texas at Austin EE360N Fall 2008, Computer Architecture.∗ The notes capture the class discussion and may contain erroneous and unverified information and comments. Lecture 12: Virtual Memory Finale and Interrupts/Exceptions Lecture #12: October 8, 2008 Lecturer: Derek Chiou Scribe: Michael Sullivan and Peter Tran Lecture 12 of EE360N: Computer Architecture summarizes the significance of virtual memory and introduces the concept of interrupts and exceptions. As such, this document is divided into two sections. Section 1 details the key points from the discussion in class on virtual memory. Section 2 goes on to introduce interrupts and exceptions, and shows why they are necessary. 1 Review and Summation of Virtual Memory The beginning of this lecture wraps up the review of virtual memory. A broad summary of virtual memory systems is given first, in Subsection 1.1. Next, the individual components of the hardware and OS that are required for virtual memory support are covered in 1.2. Finally, the addressing of caches and the interface between the cache and virtual memory are described in 1.3. 1.1 Summary of Virtual Memory Systems Virtual memory automatically provides the illusion of a large, private, uniform storage space for each process, even on a limited amount of physically addressed memory. The virtual memory space available to every process looks the same every time the process is run, irrespective of the amount of memory available, or the program’s actual placement in main memory.
    [Show full text]
  • Chapter 15 Functional Programming
    Topics Chapter 15 Numbers n Natural numbers n Haskell numbers Functional Programming Lists n List notation n Lists as a data type n List operations Chapter 15: Functional Programming 2 Numbers Natural Numbers The natural numbers are the numbers 0, 1, Haskell provides a sophisticated 2, and so on, used for counting. hierarchy of type classes for describing various kinds of numbers. Introduced by the declaration data Nat = Zero | Succ Nat Although (some) numbers are provided n The constructor Succ (short for ‘successor’) as primitives data types, it is has type Nat à Nat. theoretically possible to introduce them n Example: as an element of Nat the number 7 through suitable data type declarations. would be represented by Succ(Succ(Succ(Succ(Succ(Succ(Succ Zero)))))) Chapter 15: Functional Programming 3 Chapter 15: Functional Programming 4 Natural Numbers Natural Numbers Every natural number is represented by a Multiplication ca be defined by unique value of Nat. (x) :: Nat à Nat à Nat m x Zero = Zero On the other hand, not every value of Nat m x Succ n = (m x n) + m represents a well-defined natural number. n Example: ^, Succ ^, Succ(Succ ^) Nat can be a member of the type class Eq Addition ca be defined by instance Eq Nat where Zero == Zero = True (+) :: Nat à Nat à Nat Zero == Succ n = False m + Zero = m Succ m == Zero = False m + Succ n = Succ(m + n) Succ m == Succ n = (m == n) Chapter 15: Functional Programming 5 Chapter 15: Functional Programming 6 1 Natural Numbers Haskell Numbers Nat can be a member of the type class Ord instance
    [Show full text]