# functional programming

120 results back to index

Scala in Action by Nilanjan Raychaudhuri

Knowing the difference between strict and nonstrict processing will help you decide which type of collection would be useful and when. The next chapter explores functional programming. You’ll learn what functional programming is and how to do functional programming in Scala. Understanding functional programming will help you build functional, immutable, and simple solutions. Chapter 5. Functional programming This chapter covers Why functional programming matters Mixing functional programming with OOP Functions in various forms Monads and their practical examples You’re already doing functional programming using Scala if you’ve been following the examples in the book. In some cases it’s explicitly mentioned or visible and in other cases it’s mixed with object-oriented constructs of the Scala language.

Parallel collection hierarchy 4.11.2. Switching between sequential and parallel collections 4.12. Summary Chapter 5. Functional programming 5.1. What is functional programming? 5.1.1. The benefits of referential transparency 5.1.2. A pure functional program 5.2. Moving from OOP to functional programming 5.2.1. Pure vs. impure programming 5.2.2. Object-oriented patterns in functional programming 5.2.3. Modeling purely functional programs 5.3. Functions in all shapes and forms 5.3.1. Methods vs. functions 5.3.2. Higher-order functions 5.3.3. Function currying 5.3.4.

In some cases it’s explicitly mentioned or visible and in other cases it’s mixed with object-oriented constructs of the Scala language. This chapter focuses on functional programming concepts and how they can be implemented in Scala. The goal of the chapter is to make you comfortable with functional programming and help you to write code in functional programming style. Functional programming is a programming paradigm that models computation as the evaluation of expressions. And expressions are built using functions that don’t have mutable state and side effects. Exploring the roots of functional programming is valuable.[1] Believe it or not, functional programming started around 1930 when Alonzo Church introduced lambda calculus.[2] A lambda calculus (λ calculus) is a formal mathematical system to investigate functions, function application, and function recursion.

pages: 210 words: 42,271

Programming HTML5 Applications by Zachary Kessin

List recursion function iterateAjax(tasks) { function iterator(tasks) { \$.ajax({ url: 'index.php', data: tasks[0], success: function(data, status, XMLHttpRequest) { if (tasks.length > 0) { // Do something with the results here iterator(tasks.slice(1)); } } }); } iterator(tasks); } Although building an entire single-page web application with only functional programming styles would not be practical, functional programming still provides many useful ideas that should not be ignored. Functional programming is very well suited, for instance, for use with Web Workers (see Chapter 8). Not a lot has been written about functional programming in JavaScript, but there is quite a lot in other languages that can be applied to JavaScript. For more on functional programming, see these books: Real World Haskell by Bryan O’Sullivan, John Goerzen, and Donald Bruce Stewart (O’Reilly) Programming Scala by Dean Wampler and Alex Payne (O’Reilly) Structure and Interpretation of Computer Programs by Harold Abelson and Gerald Jay Sussman (MIT Press) Prototypes and How to Expand Objects Everything in JavaScript can have methods attached to it.

In this case, it shows that we have clicked on the “delete” button and lists the reference to the jQuery object for the button itself. Figure 2-1. Closures in Google Chrome’s DevTools Functional Programming Functional programming is a methodology that is more commonly associated with languages like Lisp, Scala, Erlang, F#, or Haskell, but works quite well in JavaScript also. Functional programming rests on a couple basic assumptions: Functions are first-class citizens of the language and can be used where any other value can be used. Complex behavior can be built by composition of simple functions.

pages: 303 words: 57,177

Hands-On Functional Programming in RUST by Andrew Johnson

For more information about Packt, please visit packtpub.com. Functional Programming – a Comparison Functional programming (FP) is the second most popular programming paradigm, behind only object-oriented programming (OOP). For many years, these two paradigms have been separated into different languages, so as not to be mixed. Multi-paradigm languages have attempted to support both approaches. Rust is one such language. As a broad definition, functional programming emphasizes the use of composable and maximally reusable functions to define program behavior. Using these techniques, we will show how functional programming has adapted clever solutions to many common yet difficult problems.

Hands-On Functional Programming in Rust Build modular and reactive applications with functional programming techniques in Rust 2018 Andrew Johnson BIRMINGHAM - MUMBAI Hands-On Functional Programming in Rust Copyright © 2018 Packt Publishing All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews. Every effort has been made in the preparation of this book to ensure the accuracy of the information presented.

Using typesafe interfaces instead of stringly typed interfaces Using the heartbeat pattern for long running processes Validating input and output Finding and fixing bugs Metaprogramming Summary Questions Assessments Functional Programming&#xA0;&#x2013; a Comparison Functional Control Flow Functional Data Structures Generics and Polymorphism Code Organization and Application Architecture Mutability, Ownership, and Pure Functions Design Patterns Implementing Concurrency Performance, Debugging, and Metaprogramming Other Books You May Enjoy Leave a review - let other readers know what you think Preface Thanks for your interest in functional programming in Rust. Rust is a very young programming language and is particularly new to the functional programming community. Despite its age, the language provides a wealth of tools that are both practical and sophisticated.

pages: 448 words: 71,301

Programming Scala by Unknown

Package Objects Sealed Class Hierarchies The Scala Type Hierarchy Linearization of an Object’s Hierarchy Recap and What’s Next 145 148 150 151 155 159 164 8. Functional Programming in Scala . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165 What Is Functional Programming? Functions in Mathematics Variables that Aren’t Functional Programming in Scala Function Literals and Closures Purity Inside Versus Outside Recursion Tail Calls and Tail-Call Optimization Trampoline for Tail Calls Functional Data Structures Lists in Functional Programming Maps in Functional Programming Sets in Functional Programming Other Data Structures in Functional Programming Traversing, Mapping, Filtering, Folding, and Reducing Traversal Mapping Filtering Folding and Reducing Functional Options Pattern Matching Partial Functions Currying Implicits Implicit Conversions Implicit Function Parameters Final Thoughts on Implicits Call by Name, Call by Value Lazy Vals Recap: Functional Component Abstractions x | Table of Contents Download at WoweBook.Com 165 166 166 167 169 169 170 171 172 172 173 173 174 174 174 175 175 178 179 181 182 183 184 186 186 188 189 189 190 192 9.

Long the topic of computer science research and even older than object-oriented programming, functional programming offers effective techniques for concurrent programming, which is growing in importance. Because functional programming is less widely understood than object-oriented programming, we won’t assume that you have prior experience with it. We’ll start this chapter with plenty of background information. As you’ll see, functional programming is not only a very effective way to approach concurrent programming, which we’ll explore in depth in Chapter 9, but functional programming can also improve your objects. Of course, we can’t provide an exhaustive introduction to functional programming.

Of course, we can’t provide an exhaustive introduction to functional programming. To learn more about it, [O’Sullivan2009] has a more detailed introduction in the context of the Haskell language. [Abelson1996], [VanRoy2004], and [Turbak2008] offer thorough introductions to general programming approaches, including functional programming. Finally, [Okasaki1998] and [Rabhi1999] discuss functional data structures and algorithms in detail. What Is Functional Programming? Don’t all programming languages have functions of some sort? Whether they are called methods, procedures, or GOTOs, programmers are always dealing in functions. 165 Download at WoweBook.Com Functional programming is based on the behavior of functions in the mathematical sense, with all the implications that starting point implies.

Practical OCaml by Joshua B. Smith

That day might not belong to functional programming languages, but it is likely that functional programming will continue to affect the programming world. It will most certainly affect the programmers of the world, which is more important, anyway. Chapter 20 discusses functional programming in particular. You have seen that OCaml is not purely functional; in the next chapter you will see that OCaml is quite functional. 620Xch20final.qxd 9/22/06 12:18 AM CHAPTER Page 261 20 ■■■ Digression: Functional Programming A t various points in this book, I noted that OCaml is a functional programming language. Chapter 19 told you that OCaml is not a purely functional programming language and what that lack of purity is about.

This is even truer for highly concurrent programs that might be impossible for a human being to adequately understand in any way. Conclusion Although functional programming is not the only style of programming that can solve problems, it does have specific merits. Functional programs can be shorter than OOP programs and easier to understand. They also make writing defect-free programs easier because the code is shorter and the components are modular. Functional programming encourages a bottom-up design that can be flexible and enables you to create programs that can adapt to changing requirements and environments. Functional programming is not the only style of programming available, but because this book is about a functional programming language, it is biased toward functional programming solutions.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251 Purely Functional Data Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . 252 Languages Like OCaml. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 xv 620Xfmfinal.qxd xvi 9/22/06 4:21 PM Page xvi ■CONTENTS Languages Like Haskell . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253 Benefits of Impurity . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Hiding the Impure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Preventing Information Leaks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 260 ■CHAPTER 20 Digression: Functional Programming . . . . . . . . . . . . . . . . . . . . . 261 Overview of Programming Styles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261 Structured Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Object-Oriented Programming. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 262 Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 263 Advantages of Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . 266 Less Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 267 Fewer Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 268 Programming in the Large . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 270 Correctness of Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Concurrency . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271 Reasoning About Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 Conclusion . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 272 ■CHAPTER 21 Practical: Web Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 273 What Does Web Programming Mean?

pages: 496 words: 174,084

Masterminds of Programming: Conversations With the Creators of Major Programming Languages by Federico Biancuzzi, Shane Warden

In that sense object-oriented programming is a problem, but you could do object-oriented programming with immutable objects. Then you wouldn’t have these same problems. That’s kind of what functional programming languages are doing, for example. Regarding your interest in functional programming, should computer science students study more math and experiment more with functional programming? Anders: Well, I certainly think that it is important to include functional programming in any computer science curricula. Whether you start with it that depends. I’m not sure that your very first introduction to programming should be functional programming, but I definitely think that it ought to be part of a curriculum. What lessons should people learn from your experience?

pages: 184 words: 13,957

Programming in Haskell by Graham Hutton

The Computer Journal, 43(4), 2000. 11. Paul Hudak. Conception, Evolution and Application of Functional Programming Languages. Communications of the ACM, 21(3): 359–411, 1989. 12. Gerard Huet. The Zipper. Journal of Functional Programming, 7(5): 549–554, September 1997. 13. John Hughes. Why Functional Programming Matters. The Computer Journal, 32(2): 98–107, 1989. 14. Graham Hutton. A Tutorial on the Universality and Expressiveness of Fold. Journal of Functional Programming, 9(4): 355–372, 1999. 15. Graham Hutton. The Countdown Problem. Journal of Functional Programming, 12(6): 609–616, 2002. 16. Graham Hutton and Erik Meijer. Monadic Parser Combinators.

r Written by a leading Haskell researcher and instructor, well known for his teaching skills r Can be used with courses, or as a stand-alone text for self-learning Graham Hutton has worked in four of the leading centres for research and teaching on functional programming. He has more than 15 years of experience in functional programming research, during which time he has published more than 30 research articles, chaired the Haskell Workshop, and edited a special issue on Haskell of the Journal of Functional Programming. He also has more than 10 years’ experience in teaching Haskell, and in promoting the use of functional programming in the curriculum. Programming in Haskell Graham Hutton University of Nottingham CAMBRIDGE UNIVERSITY PRESS Cambridge, New York, Melbourne, Madrid, Cape Town, Singapore, São Paulo Cambridge University Press The Edinburgh Building, Cambridge CB2 8RU, UK Published in the United States of America by Cambridge University Press, New York www.cambridge.org Information on this title: www.cambridge.org/9780521871723 © G.

In general, the order in which functions are applied in a calculation does not affect the value of the ﬁnal result, but it may affect the number of steps required, and may affect whether the calculation process terminates. These issues are explored in more detail in chapter 12. 1.2 Functional programming What is functional programming? Opinions differ, and it is difﬁcult to give a precise deﬁnition. Generally speaking, however, functional programming can be viewed as a style of programming in which the basic method of computation is the application of functions to arguments. In turn, a functional programming language is one that supports and encourages the functional style. To illustrate these ideas, let us consider the task of computing the sum of the integers (whole numbers) between one and some larger number n .

pages: 706 words: 120,784

The Joy of Clojure by Michael Fogus, Chris Houser

Chapter 7 will tackle Clojure’s approach to functional programming full-on. For those of you coming from a functional programming background, much of the chapter will be familiar, although Clojure will present its own unique blend. But like every programming language dubbed “functional,” Clojure’s implementation will provide a different lens by which to view your previous experience. For those of you wholly unfamiliar with functional programming techniques, chapter 7 will likely be mind-bending. In coming from a language that centers on object hierarchies and imperative programming techniques, the notion of functional programming seems alien.

The Clojure way 1.1.1. Simplicity 1.1.2. Freedom to focus 1.1.3. Empowerment 1.1.4. Clarity 1.1.5. Consistency 1.2. Why a(nother) Lisp? 1.2.1. Beauty 1.2.2. Extreme flexibility 1.2.3. Code is data 1.3. Functional programming 1.3.1. A workable definition of functional programming 1.3.2. The implications of functional programming 1.4. Why Clojure isn’t especially object-oriented 1.4.1. Defining terms 1.4.2. Imperative “baked in” 1.4.3. Most of what OOP gives you, Clojure provides 1.5. Summary Chapter 2. Drinking from the Clojure firehose 2.1.

Lisp’s homoiconicity takes a great conceptual leap in order to fully grasp, but we’ll lead you toward that understanding throughout this book in hopes that you too will come to realize the inherent power. There’s a joy in learning Lisp for the first time, and if that’s your experience coming into this book then we welcome you—and envy you. 1.3. Functional programming Quick, what does functional programming mean? Wrong answer. Don’t be too discouraged, however—we don’t really know the answer either. Functional programming is one of those computing terms[5] that has a nebulous definition. If you ask 100 programmers for their definition, you’ll likely receive 100 different answers. Sure, some definitions will be similar, but like snowflakes, no two will be exactly the same.

pages: 554 words: 108,035

Scala in Depth by Tom Kleenex, Joshua Suereth

It’s an area of software design and architecture that has been neglected in mainstream books and classes since the emergence of object-oriented programming. Functional programming offers a lot to the object-oriented developer and can nicely complement standard object-oriented practices. Functional programming is a relatively large topic to try to compress into a single chapter. Instead, this chapter introduces a few key abstractions used in functional programming and demonstrates their usage in two different situations. The goal is to show one of the many styles of functional programming, rather than turn you into an expert functional programmer. First, a discussion on some fundamental concepts behind the patterns in functional programming. 11.1.

This means that developers can make direct use of existing Java libraries and integrate Scala into their Java applications while also gaining the additional power of Scala. This integration makes Scala a practical choice for any JVM-based project. Let’s take a deeper look at the blending of paradigms in Scala. 1.1. Functional programming meets object orientation Functional programming and object-oriented programming are two different ways of looking at a problem. Functional programming puts special emphasis on the “verbs” of a program and ways to combine and manipulate them. Object-oriented programming puts special emphasis on “nouns” and attaches verbs to them. The two approaches are almost inverses of each other, with one being “top down” and the other “bottom up.”

The code focuses on the nouns and their actions: Cat.eat(), Cat.catch(...). In functional programming, the focus is on the verbs. Functional programming approaches software as the combination and application of functions. It tends to decompose software into behaviors, or actions that need to be performed, usually in a bottom-up fashion. Functions are viewed in a mathematical sense, purely operations on their input. All variables are considered immutable. This immutability aids concurrent programming. Functional programming attempts to defer all side effects in a program as long as possible. Removing side effects makes reasoning through a program simpler, in a formal sense.

Functional Programming in Scala by Paul Chiusano, Rúnar Bjarnason

www.it-ebooks.info MEAP Edition Manning Early Access Program Functional Programming in Scala version 10 Copyright 2013 Manning Publications For more information on this and other Manning titles go to www.manning.com www.it-ebooks.info brief contents PART 1: INTRODUCTION TO FUNCTIONAL PROGRAMMING 1. What is functional programming? 2. Getting Started 3. Functional data structures 4. Handling errors without exceptions 5. Strictness and laziness 6. Purely functional state PART 2: FUNCTIONAL DESIGN AND COMBINATOR LIBRARIES 7. Purely functional parallelism 8. Property-based testing 9. Parser combinators PART 3: FUNCTIONAL DESIGN PATTERNS 10.

There are chapter notes (which includes references to external resources) and www.it-ebooks.info 4 several appendix chapters after Part 4. Throughout the book we provide references to this supplementary material, which you can explore on your own if that interests you. Have fun and good luck. www.it-ebooks.info 5 1 What is Functional Programming? 1.1 The fundamental premise of functional programming Functional programming (FP) is based on a simple premise with far-reaching implications: We construct our programs using only pure functions. In other words, functions that have no side effects. What does this mean exactly? Performing any of the following actions directly would involve a side effect: Reassigning a variable Modifying a data structure in place Setting a field on an object Throwing an exception or halting with an error Printing to the console or reading user input Reading from or writing to a file Drawing on the screen Consider what programming would be like without the ability to do these things.

www.it-ebooks.info 32 Index Terms annonymous function block curried form currying function literals higher-order function import lambda lambda expression lambda notation left-hand side method definition method signature module monomorphic monomorphism namespace object package partial application proper tail-calls REPL right-hand side self-recursion singleton type string interpolation tail-call optimization tail position type parameters uncurry uncurry underscore syntax val keyword www.it-ebooks.info 33 3 Functional data structures 3.1 Introduction We said in the introduction that functional programs do not update variables or modify data structures. This raises pressing questions—what sort of data structures can we use in functional programming, how do we define them in Scala, and how do we operate over these data structures? In this chapter we will learn the concept of a functional data structure and how to define and work with such structures. We'll use this as an opportunity to introduce how data types are defined in functional programming, learn about the related technique of pattern matching, and get practice writing and generalizing pure functions.

pages: 536 words: 73,482

Programming Clojure by Stuart Halloway, Aaron Bedra

And yet, pure functional languages like Haskell have not taken over the world, because developers find that not everything fits easily into the pure functional view. There are four reasons that Clojure can attract more interest now than functional languages have in the past: Functional programming is more urgent today than ever before. Massively multicore hardware is right around the corner, and functional languages provide a clear approach for taking advantage of it. Functional programming is covered in Chapter 4, ​Functional Programming​. Purely functional languages can make it awkward to model state that really needs to change. Clojure provides a structured mechanism for working with changeable state via software transactional memory and refs (), agents (), atoms (), and dynamic binding ().

Clojure’s dynamic typing makes it more accessible for programmers learning functional programming. Clojure’s Java invocation approach is not functional. When you call Java, you enter the familiar, mutable world. This offers a comfortable haven for beginners learning functional programming and a pragmatic alternative to functional style when you need it. Java invocation is covered in Chapter 9, ​Java Down and Dirty​. Clojure’s approach to changing state enables concurrency without explicit locking and complements Clojure’s functional core. Clojure Simplifies Concurrent Programming Clojure’s support for functional programming makes it easy to write thread-safe code.

[32] http://clojure.org/data_structures Copyright © 2012, The Pragmatic Bookshelf. Chapter 4 Functional Programming Functional programming (FP) is a big topic, not to be learned in twenty-one days[33] or in a single chapter of a book. Nevertheless, you can reach a first level of effectiveness using lazy and recursive techniques in Clojure fairly quickly, and that is what we’ll accomplish this chapter. Here’s how we’ll do that: In Section 4.1, ​Functional Programming Concepts​, you’ll get a quick overview of FP terms and concepts. This section also introduces the “Six Rules of Clojure FP” that we will refer to throughout the chapter.

Programming in Haskell by Graham Hutton

Hutton, “A Tutorial on the Universality and Expressiveness of Fold,” Journal of Functional Programming, vol. 9, no. 4, 1999. [11]G. Hutton and J. Wright, “Calculating an Exceptional Machine,” in Trends in Functional Programming Volume 5. Intellect, 2006. [12]G. Huet, “The Zipper,” Journal of Functional Programming, vol. 7, no. 5, 1997. [13]G. Hutton, “The Countdown Problem,” Journal of Functional Programming, vol. 12, no. 6, 2002. [14]R. Bird and S.-C. Mu, “Countdown: A Case Study in Origami Programming,” Journal of Functional Programming, vol. 15, no. 5, 2005. [15]S. Peyton Jones, “Tackling the Awkward Squad: Monadic Input/Output, Concurrency, Exceptions, and Foreign-Language Calls in Haskell,” in Engineering Theories of Software Construction.

In the 1950s, John McCarthy developed Lisp (“LISt Processor”), generally regarded as being the first functional programming language. Lisp had some influences from the lambda calculus, but still retained the concept of variable assignment as a central feature of the language. In the 1960s, Peter Landin developed ISWIM (“If you See What I Mean”), the first pure functional programming language, based strongly on the lambda calculus and having no variable assignments. In the 1970s, John Backus developed FP (“Functional Programming”), a functional programming language that particularly emphasised the idea of higher-order functions and reasoning about programs.

Similarly, using one effect such as concurrency or input/output we can simulate other effects such as mutability. John Hughes famously stated in his classic paper Why Functional Programming Matters that we cannot make a language more powerful by eliminating features. To that, we add that often we cannot even make a language less powerful by removing features. In this book, Graham demonstrates convincingly that the true value of functional programming lies in leveraging first-class functions to achieve compositionality and equational reasoning. Or in Graham’s own words, “functional programming can be viewed as a style of programming in which the basic method of computation is the application of functions to arguments”.

pages: 230

Purely Functional Data Structures by Chris Okasaki

Journal of the ACM, 39(3):617-648, July 1992. (p. 2) [BC93] F. Warren Burton and Robert D. Cameron. Pattern matching with abstract data types. Journal of Functional Programming, 3(2): 171-190, April 1993. (p. 180) [Bel57] Richard Bellman. Dynamic Programming. Princeton University Press, 1957. (p. 37) [BH89] Bror Bjerner and Soren Holmstrom. A compositional approach to time analysis of first order lazy functional programs. In Conference on Functional Programming Languages and Computer Architecture, pages 157-165, September 1989. (p. 82) 207 208 [BO96] [Bro78] [Bro95] [Bro96] [BST95] [BT95] [Buc93] [Bur82] [But83] [BW88] [CG93] [CLR90] [CM95] Bibliography Gerth St0lting Brodal and Chris Okasaki.

Butler. Computer response time and user performance. In Conference on Human Factors in Computing Systems, pages 5862, December 1983. (p. 83) Richard S. Bird and Philip Wadler. Introduction to Functional Programming. Prentice Hall International, 1988. (p. 29) Tyng-Ruey Chuang and Benjamin Goldberg. Real-time deques, multihead Turing machines, and purely functional programming. In Conference on Functional Programming Languages and Computer Architecture, pages 289-298, June 1993. (pp. 109,113) Thomas H. Cormen, Charles E. Leiserson, and Ronald L. Rivest. Introduction to algorithms. MIT Press, 1990. (p. 27) Richard H.

Journal of Functional Programming, 2(4):505-513, October 1992. (pp.44,109,113) John E. Hopcroft and Jeffrey D. Ullman. Set merging algorithms. SI AM Journal on Computing, 2(4): 294-303, December 1973. (p. 37) John Hughes. Lazy memo functions. In Conference on Functional Programming Languages and Computer Architecture, volume 201 of LNCS, pages 129-146. Springer-Verlag, September 1985. (p. 37) John Hughes. A novel representation of lists and its application to the function "reverse". Information Processing Letters, 22(3): 141-144, March 1986. (p. 169) John Hughes. Why functional programming matters.

pages: 263 words: 20,730

Exploring Python by Timothy Budd

Each differs from the imperative paradigm not in the way the computer operates, but in the way that the programmer thinks about the task of programming. The Functional Programming Paradigm The term functional programming does not simply imply programming with functions, but is used to describe an alternative to the imperative programming paradigm. As the name suggests, the creation of functions is an important part of functional programming. But simply defining a few functions does not mean that you are programming in a functional style. There were many functions defined in earlier chapters, and yet we did not call those functional programs. The key characteristic of a program developed in the functional programming style is that it creates new values by a process of transformation.

By emphasizing transformation, rather than modification, functional programs work on a larger scale. Transformations are often more uniform, and much simpler to write and debug. Errors, when they do occur, tend to be larger and thus easier to find and eliminate. The difference between a functional and an imperative style is best illustrated by examples, as we will shortly present. Mapping, Filtering and Reduction The process of transformation can be subdivided into several common forms. The three most common varieties of transformation are mapping, filtering, and reduction. Exploring Python – Chapter 8: Functional Programming 1 A mapping is a one to one transformation.

The following illustrates the application of each of these functions: >>> >>> [3, >>> [2, a = [1, 2, 3, 4, 5] print map(lambda x : x * 2 + 1, a) 5, 7, 9, 11] print filter(lambda x: x % 2 == 0, a) 4] Exploring Python – Chapter 8: Functional Programming 2 >>> print reduce(lambda x, y: x + y, a) 15 Notice that the original list, held in the variable named a, remains unchanged. The functions map, filter and reduce produce new lists that are transformations of the argument. The function filter requires an argument that is itself a function that takes only one argument, and returns a Boolean value. A one-argument function that returns a Boolean result is termed a predicate. List Comprehensions An even simpler form of functional programming is provided by a list comprehension. Instead of defining a list by a sequence of elements, lists can be characterized by a process.

pages: 647 words: 43,757

Types and Programming Languages by Benjamin C. Pierce

It also includes a description of System F from its creator, and an appendix introducing linear logic. Connections between types and logic are further explored in Pfenning's Computation and Deduction (2001). Thompson's Type Theory and Functional Programming (1991) and Turner's Constructive Foundations for Functional Languages (1991) focus on connections between functional programming (in the "pure functional programming" sense of Haskell or Miranda) and constructive type theory, viewed from a logical perspective. A number of relevant topics from proof theory are developed in Goubault-Larrecq and Mackie's Proof Theory and Automated Deduction (1997).

Girard, Jean-Yves, Yves Lafont, and Paul Taylor. Proofs and Types, volume 7 of Cambridge Tracts in Theoretical Computer Science. Cambridge University Press, 1989. Glew, Neal. Type dispatch for named hierarchical types. In International Conference on Functional Programming (ICFP), Paris, France,pages 172–182, 1999. Gordon, Andrew. A tutorial on co-induction and functional programming. In Functional Programming, Glasgow 1994, pages 78–95. Springer Workshops in Computing, 1995. Gordon, Michael J. Adding eval to ML. Manuscript, circa 1980. Gordon, Michael J., Robin Milner, and Christopher P. Wadsworth. Edinburgh LCF. Springer-Verlag LNCS 78, 1979.

Unlike the object encodings that we have already encountered in Chapter 18, all the examples in this section are purely functional programs. This is purely an expository choice: mechanisms for modularity and abstraction are almost completely orthogonal to the statefulness or statelessness of the abstractions being defined. (Exercises 24.2.2 and 24.2.4 illustrate this point by developing stateful versions of some of the purely functional examples in the text.) The reasons for preferring purely functional examples here are that (1) this choice implies that our examples live in a simpler and more economical formal framework, and (2) working with purely functional programs sometimes makes the typing problems more interesting (and their solutions correspondingly more revealing).

pages: 999 words: 194,942

Clojure Programming by Chas Emerick, Brian Carper, Christophe Grand

channels=#clojure if you aren’t on IRC regularly enough to maintain a desktop client. Part I. Functional Programming and Concurrency Chapter 2. Functional Programming Functional programming (FP) is one of those amorphous concepts in software development that means different things to different people. Despite the many shades of gray that exist in the FP spectrum, it’s easy to assert that Clojure is a functional programming language, and that that character is the root of many of its most attractive facilities and advantages. In this chapter, we will: Give you a reasonable introduction to what functional programming is Explain why you should care about it Discuss the details of Clojure’s implementation that make it a desirable functional programming language Along the way, we hope to make the case that FP—and Clojure’s flavor of FP in particular—far from being an academic exercise, can improve your practice of software design and development just as structural- and object-oriented programming concepts have over the years.

fixtures, Fixtures flow, The Persistent, Evolving Environment fn, Creating Functions: fn, Function literals, Preconditions and Postconditions for, Collection form-level comments, Comments forms, Comments, Comments, Special Forms, Dynamic Scope, Macroexpansion, Choosing Clojure Type Definition Forms Wisely (see also special forms) comment forms, Comments concurrency forms, Dynamic Scope expanding nested forms, Macroexpansion println forms, Comments type definition forms, Choosing Clojure Type Definition Forms Wisely forward declarations, Forward Declarations FP (functional programming), Functional Programming, Functional Programming in the Real World, What Does Functional Programming Mean?, On the Importance of Values, A Critical Choice, About Values, Comparing Values to Mutable Objects, Comparing Values to Mutable Objects, A Critical Choice, First-Class and Higher-Order Functions, Applying Ourselves Partially, Composition of Function(ality), Building a Primitive Logging System with Composable Higher-Order Functions, Writing Higher-Order Functions, Building a Primitive Logging System with Composable Higher-Order Functions, Building a Primitive Logging System with Composable Higher-Order Functions, Pure Functions about, What Does Functional Programming Mean?

If you are completely new to FP or initially skeptical of it, we’d urge you in particular to hang on for the ride, it’ll be worth your time and effort.[35] Recall again from Chapter 1 the adage Clojure demands that you raise your game, and pays you back for doing so; just as you may have had to grow to learn object-oriented programming, or Java generics, or Ruby, you’ll have to reach a little to be able to understand and make the most of FP—and therefore Clojure. But in return, you’ll have not just a “new way of thinking,” but a set of tools and practices highly applicable to day-to-day programming challenges.[36] What Does Functional Programming Mean? Functional programming is an umbrella term that encompasses a number of language-level primitives and capabilities of which different languages provide different treatments. In Clojure, functional programming means: A preference for working with immutable values; this includes: The use of immutable data structures that satisfy simple abstractions, rather than mutable bags of state The treatment of functions as values themselves, enabling higher-order functions A preference for declarative processing of data over imperative control structures and iteration The natural incremental composition of functions, higher-order functions, and immutable data structures in order to solve complex problems by working with higher-level (or, right-level) abstractions These are all part of the foundation for many of the more advanced features of Clojure that you may have heard of—in particular, Clojure’s fantastic support for concurrency, parallelism, and more generally, providing defined semantics for the management of identities and changing state, which we’ll cover separately in Chapter 4

pages: 680 words: 157,865

Beautiful Architecture: Leading Thinkers Reveal the Hidden Beauty in Software Design by Diomidis Spinellis, Georgios Gousios

The success of object technology has largely followed from the marked improvements it brings—if applied properly as a method, not just through the use of an object-oriented programming language—to the reliability, extendibility, and reusability of the resulting programs. The functional programming approach predates object-oriented thinking, going back to the Lisp language available for almost 50 years. To those fortunate enough to have learned it early, functional programming will always remain like the memory of a first kiss: sweet, and the foretaste of even better experiences. Functional programming has made a comeback in recent years, with the introduction of new languages such as Scheme, Haskell, OCaml and F#, sophisticated type systems, and advanced language mechanisms such as monads. Functional programming even seems at times to be presented as an improvement over object-oriented techniques.

Using types as the basic modularization mechanism, as in object-oriented design, will elevate the level of abstraction. Levels of Modularity Assessing functional programming against criteria of modularity is legitimate since better modularization is one of the main arguments for the approach. We have seen the presentation’s comments on this issue, but here is a more general statement from one of the foundational papers of functional programming, by Hughes (1989), stating that with this approach: [Programs] can be modularized in new ways, and thereby greatly simplified. This is the key to functional programming’s power—it allows greatly improved modularization. It is also the goal for which functional programmers must strive—smaller and simpler and more general modules, glued together with the new glues we shall describe.

Modern functional languages showed the benefit of accepting higher-order functionals as regular program objects, and developed the associated type systems. This is the part of functional programming that has had the most direct effect on the development of mainstream approaches to programming; as will be seen below, the notion of agent, directly derived from these functional programming concepts, is a welcome addition to the original object-oriented framework. The fourth significant attraction of functional programming is lazy evaluation: the ability, in some functional languages such as Haskell, to describe a computation that is potentially infinite, with the understanding that any concrete execution of that computation will be finite.

pages: 226 words: 17,533

Programming Scala: tackle multicore complexity on the JVM by Venkat Subramaniam

You can quickly put to use the powerful capabilities of Scala, including sensible static typing, closures, immutable collections, and elegant pattern matching. Scala’s support for functional programming helps you to write concise and expressive code. Thanks to the higher level of abstraction, you can get more things done with fewer lines of code. The functional style will benefit both your single-threaded applications and your multithreaded applications. A number of functional programming languages exist. Erlang, for one, is a nice functional programming language. In fact, Scala’s concurrency model is very similar to that of Erlang. However, Scala has two significant advantages over Erlang.

This distinction has a far-reaching consequence. Because the language does not do more, you are able to do a lot more with it. It is truly extensible, and its library serves as a case study for that. 1.3 Functional Programming I’ve mentioned that Scala can be used as a functional programming language a couple of times already. I want to take a few pages to give you a little of the flavor of functional programming. Let’s start by contrasting it with the imperative style of Java programming. If we want to find the maximum temperature for a given day, we could write Java code like this: //Java code public static int findMax(List<Integer> temperatures) { int highTemperature = Integer.MIN_VALUE; for(int temperature : temperatures) { highTemperature = Math.max(highTemperature, temperature); } return highTemperature; } We created the mutable variable highTemperature and continually modified it in the loop.

When you have mutable variables, you have to ensure Download at Boykma.Com Report erratum Prepared exclusively for sam kaplan this copy is (P1.0 printing, June 2009) 19 F UNCTIONAL P ROGRAMMING you initialize them properly and are changing them in the right place to the right values. Functional programming is a declarative style in which you say what to do instead of how something should be done. You’ve used functional style if you’ve used XSLT, a rules engine, or ANTLR. We can rewrite the previous code in functional style with no mutable variables as follows: Download Introduction/FindMaxFunctional.scala def findMax(temperatures : List[Int]) = { temperatures.foldLeft(Integer.MIN_VALUE) { Math.max } } You are seeing an interplay of Scala conciseness and functional programming style in the previous code. That’s some dense code.

Pearls of Functional Algorithm Design by Richard Bird

Countdown was ﬁrst studied in an earlier pearl (Hutton, 2002) as an illustration of how to prove that functional programs meet their speciﬁcation. Hutton’s aim was not to derive the best possible algorithm, but to present one whose correctness proof required only simple induction. Essentially, Hutton’s proof dealt with the correctness of countdown2. References Bird, R. S. and Mu, S.-C. (2005). Countdown: a case study in origami programming. Journal of Functional Programming 15 (6), 679–702. Hutton, G. (2002). The Countdown problem. Journal of Functional Programming 12 (6), 609–16. 21 Hylomorphisms and nexuses Introduction It was Erik Meijer who coined the name hylomorphism to describe a computation that consists of a fold after an unfold.

These problems, some of which are completely new, are drawn from sources as diverse as games and puzzles, intriguing combinatorial tasks and more familiar algorithms in areas such as data compression and string matching. Each pearl starts with the statement of the problem expressed using the functional programming language Haskell, a powerful yet succinct language for capturing algorithmic ideas clearly and simply. The novel aspect of the book is that each solution is calculated from the problem statement by appealing to the laws of functional programming. Pearls of Functional Algorithm Design will appeal to the aspiring functional programmer, students and teachers interested in the principles of algorithm design, and anyone seeking to master the techniques of reasoning about programs in an equational style.

In LNCS 5133: Proceedings of the Ninth International Conference on the Mathematics of Program Construction, ed. P. Audebaud and C. Paulin-Mohring. pp. 92–109. Meijer, E. (1992). Calculating compilers. PhD thesis, Nijmegen University, The Netherlands. Meijer, E., Fokkinga, M. and Paterson, R. (1991). Functional programming with bananas, lenses, envelopes and barbed wire. Proceedings of the 5th ACM Conference on Functional Programming Languages and Computer Architecture. New York, NY: Springer-Verlag, pp. 124–44. 22 Three ways of computing determinants Introduction The determinant, det(A), or |A|, of an n ×n matrix A = (aij ) can be deﬁned by the Leibniz formula |A| = sign (π) aj π(j ) π 1≤j ≤n The sum is taken over all permutations π of [1 .. n] and sign (π) = 1 for even permutations (those that have an even number of inversions), and −1 for odd ones.

pages: 214 words: 14,382

Monadic Design Patterns for the Web by L.G. Meredith

Note that all of those languages are either functional languages or object-functional languages, and that most proposals are either functional, object-functional, or heavily influenced by functional language design concepts. Advances in FP: monads, and the awkward squad Perhaps a chief reason for the popularity of functional programming language design is that the core of the functional model is inherently simple. The rules governing the execution of functional programs (the basis of an abstract evaluator) can be stated in half a page. In some sense, functional language design is a “path of least resistance” approach. A deeper reason for adopting functional language design is that the core model is compositional; that is, enriching the execution semantics amounts to the enrichment of the semantics’ components.

eBook <www.wowebook.com> 2.3 Core design patterns First, a little history: Haskell was the first programming language to popularize the notion of monad as a structuring technique for functional programming. It packaged this notion with several key ideas. One was to treat the core elements that make up a monad more or less directly without appeal to category theory – the branch of mathematics in which the notion originated. This is considerably easier to do in a functional programming language because you can think of the ambient language as a category; thus, the average programmer doesn’t need to refer to categories, in general, but only to the universe of programs that can be written in the language at hand.

This approach provides a much more elegant solution, allowing us to expand our notion of stateless to “just stateful enough” in a way that faithfully aligns with the semantics of functional programming languages, themselves. Offering just a single doubloon of the treasures that lie behind this basic enrichment, allow me to say something about the correspondence of this idea to games semantics. In the world of programming language semantics, one of the most successful paradigms for reasoning about the semantics of functional programming languages is games semantics, which carves up the world of computations into a few basic components: Player (which we know as client), Opponent (which we know as server), Question (which we have been calling request), and Answer (response).

pages: 423 words: 21,637

On Lisp: Advanced Techniques for Common Lisp by Paul Graham

The body is evaluated with the variables bound to the respective return values from the call: > (multiple-value-bind (int frac) (truncate 26.21875) (list int frac)) (26 0.21875) Finally, to return multiple values, we use the values operator: > (defun powers (x) (values x (sqrt x) (expt x 2))) POWERS > (multiple-value-bind (base root square) (powers 4) (list base root square)) (4 2.0 16) Functional programming is a good idea in general. It is a particularly good idea in Lisp, because Lisp has evolved to support it. Built-in operators like reverse and nreverse are meant to be used in this way. Other operators, like values and multiple-value-bind, have been provided specifically to make functional programming easier. 3.2 Imperative Outside-In The aims of functional programming may show more clearly when contrasted with those of the more common approach, imperative programming. A functional program tells you what it wants; an imperative program tells you what to do.

The second node, mods/n, can either look for more nouns, or return a parsing. Section 3.4 explained how writing programs in a functional style makes them easier to test: In a functional program, components can be tested individually. In Lisp, functions can be tested interactively, in the toplevel loop. Together these two principles allow interactive development: when we write functional programs in Lisp, we can test each piece as we write it. ATNs are so like functional programs--in this implementation, they macroexpand into functional programs--that the possibility of interactive development applies to them as well. We can test an ATN starting from any node, simply by giving its name as the first argument to with-parses: > (with-parses mods '(time arrow) (format t "Parsing: ~A~%" parse)) Parsing: (N-GROUP (ARROW TIME)) The next two networks have to be discussed together,because they are mutually recursive.

The character of Lisp functions has a similar influence on the structure of Lisp programs. Functional programming means writing programs which work by returning values instead of by performing side-effects. Side-effects include destructive changes to objects (e.g. by rplaca) and assignments to variables (e.g. by setq). If side-effects are few and localized, programs become easier to read, test, and debug. Lisp programs have not always been written in this style, but over time Lisp and functional programming have gradually become inseparable. An example will show how functional programming differs from what you might do in another language.

The Haskell Road to Logic, Maths and Programming by Kees Doets, Jan van Eijck, Jan Eijck

It is convenient to choose a programming language for this that permits implementations to remain as close as possible to the formal definitions. Such a language is the functional programming language Haskell [HT]. Haskell was named after the logician Haskell B. Curry. Curry, together with Alonzo Church, laid the foundations of functional computation in the era Before the Computer, around 1940. As a functional programming language, Haskell is a member of the Lisp family. Others family members are Scheme, ML, Occam, Clean. Haskell98 is intended as a standard for lazy functional programming. Lazy functional programming is a programming style where arguments are evaluated only when the value is actually needed.

Haskell emerged in the last decade as a standard for lazy functional programming, a programming style where arguments are evaluated only when the value is actually needed. Functional programming is a form of descriptive programming, very different from the style of programming that you find in prescriptive languages like C or Java. Haskell is based on a logical theory of computable functions called the lambda calculus. Lambda calculus is a formal language capable of expressing arbitrary computable functions. In combination with types it forms a compact way to denote on the one hand functional programs and on the other hand mathematical proofs.

In fact, sorts are just like the basic types in a functional programming language. Just as good naming conventions can make a program easier to understand, naming conventions can be helpful in mathematical writing. For instance: the letters n, m, k, . . . are often used for natural numbers, f, g, h, . . . usually indicate that functions are meant, etc. The interpretation of quantifiers in such a case requires that not one, but several domains are specified: one for every sort or type. Again, this is similar to providing explicit typing information in a functional program for easier human digestion. Exercise 2.50 That the sequence a0 , a1 , a2 , . . . ∈ R converges to a, i.e., that limn→∞ an = a, means that ∀δ > 0∃n∀m > n(|a − am | < δ).

pages: 1,201 words: 233,519

Coders at Work by Peter Seibel

I think in the States you can be more collaborative for a while until you zero in on your own research program. Seibel: Speaking of research and academics, functional programming is quite popular within the research community but I think a lot of people outside that community see functional programming as being driven by ideas that, while neat, can be very mathematical and divorced from day-to-day programming. Is that a fair characterization? Peyton Jones: I think it's about half fair. I characterize functional programming—that is, purely functional programming, where side effects are somehow really relegated to a world of their own—as a radical and elegant attack on the whole enterprise of writing programs.

He learned to program on a machine with no permanent storage and only 100 memory locations, and in college he worked on both writing high-level compilers for the school's big iron and building his own primitive computers out of parts he could afford on a student's budget. But he was drawn to functional programming by a professor's demonstration of how to build doubly linked lists without using mutation and the beauty of the idea of lazy evaluation. Peyton Jones saw the ideas of functional programming “as a radical and elegant attack on the whole enterprise of writing programs”: a way, rather than “just putting one more brick in the wall,” to “build a whole new wall.” In 2004 the Association for Computing Machinery elected him a Fellow, citing his “contributions to functional programming languages.” Among the topics we covered in this interview are why he thinks functional programming shows increasing promise of changing the way software is written, why Software Transactional Memory is a much better way of writing concurrent software than locks and condition variables, and why it is so difficult, even at a place like Microsoft Research, to do real studies of whether different programming languages make programmers more or less productive.

So my big-picture justification for why it's worth some people, like me, spending a lot of time on purely functional programming, is that it shows promise. I don't want to claim that it's exactly the way that everyone will be writing programs in the future, but it shows promise. And actually I'll make the case that it shows increasing promise. I see it as, when the limestone of imperative programming is worn away, the granite of functional programming will be observed. That said, I think purely functional programming started quite geeky and academic and mathematical. The story of the last, really, 20 years—all the time I've been working on it—has been a story of becoming increasingly practical, focusing not just on abstract ideas but trying to overcome, one by one, the obstacles that prevent real-life programmers using functional programming languages for real applications.

pages: 496 words: 70,263

Erlang Programming by Francesco Cesarini

The tracing and logging facilities also give you a clear picture of how the integration is working, enabling you to debug and tune systems much more effectively. Erlang and Functional Programming The recent success of Erlang is a success for functional programming, too, because it uses functional programming principles without making a big fuss about it: they are simply the right foundation on which to build a language with concurrency designed in from the start. One of the prevalent myths in the community in the mid-1980s was that functional programming languages would be the only languages capable of working on the general-purpose parallel machines that were “just around the corner.”

The Erlang language—and in particular, its many libraries—offer more to help the programmer be as effective as possible. The various language features covered in this chapter, many of them derived from functional programming languages, are tools that will improve the productivity of a working Erlang programmer. Functional Programming for Real Erlang is a functional programming language—among other things—but what does that really mean? Prominent in Erlang are function definitions, but that’s also the case in Pascal, C, and many other languages. What makes a true functional programming language is the fact that functions can be handled just like any other sort of data. Functional data types in Erlang are called funs.

Test-driven development (TDD) has been associated with agile programming, but it would be wrong to identify the two. An informal test-driven approach has characterized functional programming since the early LISP systems: most functional programming systems have at their top level a read-evaluate-print loop, which encourages a test- or example-based approach. Erlang comes out of that tradition, with its roots in functional programming and Prolog, and the examples of interactions in the Erlang shell show this informal test-driven approach in practice. Test-driven development is not confined to the single-person project.

pages: 292 words: 62,575

97 Things Every Programmer Should Know by Kevlin Henney

(You Are Not the User) Feathers, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design, The Golden Rule of API Design Fit (Framework for Integrated Test), When Programmers and Testers Collaborate floating-point numbers, Floating-Point Numbers Aren't Real, Floating-Point Numbers Aren't Real, Floating-Point Numbers Aren't Real formatting errors, Prevent Errors Fortran, Don't Just Learn the Language, Understand Its Culture, Floating-Point Numbers Aren't Real, Know Well More Than Two Programming Languages Fowler, Interprocess Communication Affects Application Response Time frameworks, Choose Your Tools with Care, Continuous Learning getting to know, Continuous Learning free software, Put Everything Under Version Control Freeman, Code Layout Matters, Code Layout Matters, Code Layout Matters, One Binary, One Binary, One Binary Code Layout Matters, Code Layout Matters, Code Layout Matters, Code Layout Matters One Binary, One Binary, One Binary, One Binary functional programming, Apply Functional Programming Principles, Don't Just Learn the Language, Understand Its Culture, Know Well More Than Two Programming Languages G Gagnat, Pair Program and Feel the Flow, Pair Program and Feel the Flow, Pair Program and Feel the Flow Pair Program and Feel the Flow, Pair Program and Feel the Flow, Pair Program and Feel the Flow, Pair Program and Feel the Flow Garson, Apply Functional Programming Principles, Apply Functional Programming Principles, Apply Functional Programming Principles Apply Functional Programming Principles, Apply Functional Programming Principles, Apply Functional Programming Principles, Apply Functional Programming Principles Git, Put Everything Under Version Control Goodliffe, Don't Ignore That Error!

* * * [1] http://martinfowler.com/bliki/TechnicalDebtQuadrant.html Chapter 2. Apply Functional Programming Principles Edward Garson FUNCTIONAL PROGRAMMING has recently enjoyed renewed interest from the mainstream programming community. Part of the reason is because emergent properties of the functional paradigm are well positioned to address the challenges posed by our industry's shift toward multicore. However, while that is certainly an important application, it is not the reason this piece admonishes you to know thy functional programming. Mastery of the functional programming paradigm can greatly improve the quality of the code you write in other contexts.

pages: 931 words: 79,142

Concepts, Techniques, and Models of Computer Programming by Peter Van-Roy, Seif Haridi

For example: fun {One} 1 end fun {Two} 2 end try {One}={Two} catch failure(...) then {Browse caughtFailure} end The pattern failure(...) catches any record whose label is failure. 2.8 Advanced topics This section gives additional information for deeper understanding of the declarative model, its trade-oﬀs, and possible variations. 2.8.1 Functional programming languages Functional programming consists in deﬁning functions on complete values, where the functions are true functions in the mathematical sense. A language in which this is the only possible way to calculate is called a pure functional language. Let us examine how the declarative model relates to pure functional programming. For further reading on the history, formal foundations, and motivations for functional programming, we recommend the survey article by Hudak [96]. 2.8 Advanced topics 97 The λ calculus Pure functional languages are based on a formalism called the λ calculus.

Adding a concept to a computation model introduces new forms of expression, making some programs simpler, but it also makes reasoning about programs harder. For example, by adding explicit state (mutable variables) to a functional programming model we can express the full range of object-oriented programming techniques. However, reasoning about object-oriented programs is harder than reasoning about functional programs. Functional programming is about calculating values with mathematical functions. Neither the values nor the functions change over time. Explicit state is one way to model things that change over time: it provides a container whose content can be updated.

With these restrictions, the model no longer needs unbound variables. The declarative model with these restrictions is called the (strict) functional model. This model is close to well-known functional programming languages such as Scheme and Standard ML. The full range of higher-order programming techniques is pos- 98 Declarative Computation Model sible. Pattern matching is possible using the case statement. Varieties of functional programming Let us explore some variations on the theme of functional programming: The functional model of this chapter is dynamically typed like Scheme. Many functional languages are statically typed. Section 2.8.3 explains the diﬀerences between the two approaches.

Think OCaml by Nicholas Monje, Allen Downey

By this standard, OCaml does 7 about as well as possible. 1.7 Functional, as opposed to...? Functional Programming is a programming paradigm where the function is a first-class citizen. Now, this is of course a silly definition, but it’s the best we can really do for now. Another popular programming paradigm is Object-Oriented. Languages that are object-oriented, such as C++ and Python, focus rather on having “objects” and changing them. “Object” is really kind of a blanket term for all kinds of different, often custom, ways of storing data. OCaml is mostly a functional programming language. However, OCaml has support for some level of object-oriented programming, unlike it’s predecessor Caml.

But references aren’t really any more useful than variables unless you have a more meaningful way to modify them. The most accessible method of modifying references is using loops. 10.2 Looping In functional programming, we don’t really like loops. We’d much rather use recursion, and you can usually use recursion instead. However, looping can occasionally be very useful, even in otherwise mostly-functional programs. There are two primary forms of loops: the for loop and the while loop. Technically speaking, a for loop is just a particular case of a very useful while loop, but it’s also a little easier to use and a little harder to mess up, so we’ll start with that. 10.2.1 For loop Let’s look at the problem of adding itegers from 1 to n again.

3. If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3 miles at tempo (7:12 per mile) and 1 mile at easy pace again, what time do I get home for breakfast? 20 Chapter 2. Variables and Expressions Chapter 3 Functions 3.1 Function calls In the context of functional programming, a function is a named expression that performs a computation. When you define a function, you specify the name and the expression. Later, you can “call” the function by name. We have already seen one example of a function call: # float_of_int 32;; - : float = 32. The name of the function is float_of_int.

pages: 893 words: 199,542

Structure and interpretation of computer programs by Harold Abelson, Gerald Jay Sussman, Julie Sussman

Moreover, no simple model with “nice” mathematical properties can be an adequate framework for dealing with objects and assignment in programming languages. So long as we do not use assignments, two evaluations of the same procedure with the same arguments will produce the same result, so that procedures can be viewed as computing mathematical functions. Programming without any use of assignments, as we did throughout the first two chapters of this book, is accordingly known as functional programming. To understand how assignment complicates matters, consider a simplified version of the make-withdraw procedure of section 3.1.1 that does not bother to check for an insufficient amount: (define (make-simplified-withdraw balance) (lambda (amount) (set!

We do not, for example, ordinarily regard a rational number as a changeable object with identity, such that we could change the numerator and still have “the same” rational number. Pitfalls of imperative programming In contrast to functional programming, programming that makes extensive use of assignment is known as imperative programming. In addition to raising complications about computational models, programs written in imperative style are susceptible to bugs that cannot occur in functional programs. For example, recall the iterative factorial program from section 1.2.1: (define (factorial n) (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1)) Instead of passing arguments in the internal iterative loop, we could adopt a more imperative style by using explicit assignment to update the values of the variables product and counter: (define (factorial n) (let ((product 1) (counter 1)) (define (iter) (if (> counter n) product (begin (set!

Instead, ML includes a type-inferencing mechanism that uses information in the environment to deduce the data types for newly defined procedures. 73 Similarly in physics, when we observe a moving particle, we say that the position (state) of the particle is changing. However, from the perspective of the particle's world line in space-time there is no change involved. 74 John Backus, the inventor of Fortran, gave high visibility to functional programming when he was awarded the ACM Turing award in 1978. His acceptance speech (Backus 1978) strongly advocated the functional approach. A good overview of functional programming is given in Henderson 1980 and in Darlington, Henderson, and Turner 1982. 75 Observe that, for any two streams, there is in general more than one acceptable order of interleaving. Thus, technically, “merge” is a relation rather than a function – the answer is not a deterministic function of the inputs.

pages: 309 words: 65,118

Ruby by example: concepts and code by Kevin C. Baird

Exponentiation in Ruby Returning nil when a method’s operation is not possible More recursion and exit conditions Modules and Inheritance Hash.merge Class Variables Array.detect (“find first”) Subtracting Hashes Exiting the entire script with fail begin—rescue—end Downloading with open-uri Parsing XML files with regular expressions Writing to YAML files with YAML.dump Reading from YAML files with YAML.load It’s almost as if this chapter weren’t really about numbers—we covered a large amount of generically useful information, especially Modules, Class Variables, and external data storage and retrieval using either XML or YAML (or both). We’ve done a bit of functional programming already in the last two chapters, but we’ll get into the deep lambda magic in Chapter 6. 98 C ha pt er 5 6 FUNCTIONALISM WITH BLOCKS AND PROCS Ruby has two main ancestors: Smalltalk and Lisp.1 From Smalltalk, Ruby gets its heavy object orientation, which we’ve explored in some depth up to this point. From Lisp it derives several ideas from functional programming, which is a very mathematically inclined approach to programming with a few notable characteristics. First, variables tend to be defined once, without having their values changed later on.

Creating Procs with lambda Using Procs as arguments to methods Using blocks as arguments to methods, including your own new methods Using Procs as first-class functions The inspect method Nesting lambdas within other lambdas Proc.new The yield method I have a confession to make. I love object orientation for many programming tasks, but this chapter about Ruby’s functional heritage was the most fun to write so far. Functional programming has been respected in academia for decades, and it is starting to get some well-deserved attention from folks in the computer programming industry and others who are just curious about what it can do. Now that we know some functional programming techniques, let’s put them to use and even try to optimize them, which is the subject of our next chapter. Fun c ti on al is m wit h B loc ks an d Pr ocs 119 7 USING, OPTIMIZING, AND TESTING FUNCTIONAL TECHNIQUES This chapter shows some recursive and other functional solutions to simple problems, as well as some ways we can test and improve these solutions.

Chapter 3: Programmer Utilities This chapter contains tools that are useful for developers in the form of library files intended to be used by other programs. Chapter 4: Text Manipulation This chapter focuses on processing text. Chapter 5: Number Utilities This chapter focuses on primarily numeric data, including pure math and moving into recursion. Chapter 6: Functionalism with Blocks and Procs This chapter puts a heavy emphasis on functional programming, hinted at in earlier chapters. Chapter 7: Using, Optimizing, and Testing Functional Techniques This chapter details testing, profiling, and optimizing your programs. Chapter 8: HTML and XML Tools This chapter has a subset of text processing specifically meant for markup, like HTML and XML.

pages: 404 words: 43,442

The Art of R Programming by Norman Matloff

This is nice, since it means that you, as a user, have fewer commands to remember! Functional Programming As is typical in functional programming languages, a common theme in R programming is avoidance of explicit iteration. Instead of coding loops, you exploit R’s functional features, which let you express iterative behavior implicitly. This can lead to code that executes much more efﬁciently, and it can make a huge timing difference when running R on large data sets. Introduction xxi As you will see, the functional programming nature of the R language offers many advantages: • Clearer, more compact code • Potentially much faster execution speed • Less debugging, because the code is simpler • Easier transition to parallel programming Whom Is This Book For?

BRIEF CONTENTS Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix Chapter 1: Getting Started . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 Chapter 2: Vectors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25 Chapter 3: Matrices and Arrays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59 Chapter 4: Lists. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 85 Chapter 5: Data Frames . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101 Chapter 6: Factors and Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .121 Chapter 7: R Programming Structures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .139 Chapter 8: Doing Math and Simulations in R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .189 Chapter 9: Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207 Chapter 10: Input/Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .231 Chapter 11: String Manipulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .251 Chapter 12: Graphics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261 Chapter 13: Debugging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .285 Chapter 14: Performance Enhancement: Speed and Memory . . . . . . . . . . . . . . . . . . . . . . . . . . . .305 Chapter 15: Interfacing R to Other Languages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .323 Chapter 16: Parallel R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .333 Appendix A: Installing R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .353 Appendix B: Installing and Using Packages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .355 CONTENTS IN DETAIL ACKNOWLEDGMENTS xvii INTRODUCTION xix Why Use R for Your Statistical Work? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Object-Oriented Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Functional Programming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . Whom Is This Book For? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . My Own Background . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1 GETTING STARTED 1.1 1.2 1.3 1.4 1.5 1.6 1.7 How to Run R . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.1 Interactive Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1.1.2 Batch Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3 Using R Debugging Facilities . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3.1 Single-Stepping with the debug() and browser() Functions . . . . . . . . . . . 13.3.2 Using Browser Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3.3 Setting Breakpoints . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3.4 Tracking with the trace() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3.5 Performing Checks After a Crash with the traceback() and debugger() Function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13.3.6 Extended Example: Two Full Debugging Sessions . . . . . . . . . . . . . . . . . . 13.4 Moving Up in the World: More Convenient Debugging Tools . . . . . . . . . . . . . . . . . . . 285 285 286 286 287 287 288 288 289 289 291 291 292 300 Contents in Detail xiii 13.5 Ensuring Consistency in Debugging Simulation Code . . . . . . . . . . . . . . . . . . . . . . . . . . . 302 13.6 Syntax and Runtime Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 13.7 Running GDB on R Itself . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 303 14 PERFORMANCE ENHANCEMENT: SPEED AND MEMORY 305 14.1 Writing Fast R Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.2 The Dreaded for Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.2.1 Vectorization for Speedup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.2.2 Extended Example: Achieving Better Speed in a Monte Carlo Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.2.3 Extended Example: Generating a Powers Matrix . . . . . . . . . . . . . . . . . . . 14.3 Functional Programming and Memory Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.3.1 Vector Assignment Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.3.2 Copy-on-Change Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.3.3 Extended Example: Avoiding Memory Copy . . . . . . . . . . . . . . . . . . . . . . 14.4 Using Rprof() to Find Slow Spots in Your Code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.4.1 Monitoring with Rprof() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.4.2 How Rprof() Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.5 Byte Code Compilation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14.6 Oh No, the Data Doesn’t Fit into Memory!

pages: 1,387 words: 202,295

Structure and Interpretation of Computer Programs, Second Edition by Harold Abelson, Gerald Jay Sussman, Julie Sussman

Moreover, no simple model with “nice” mathematical properties can be an adequate framework for dealing with objects and assignment in programming languages. So long as we do not use assignments, two evaluations of the same procedure with the same arguments will produce the same result, so that procedures can be viewed as computing mathematical functions. Programming without any use of assignments, as we did throughout the first two chapters of this book, is accordingly known as functional programming. To understand how assignment complicates matters, consider a simplified version of the make-withdraw procedure of 3.1.1 that does not bother to check for an insufficient amount: (define (make-simplified-withdraw balance) (lambda (amount) (set!

We do not, for example, ordinarily regard a rational number as a changeable object with identity, such that we could change the numerator and still have “the same” rational number. Pitfalls of imperative programming In contrast to functional programming, programming that makes extensive use of assignment is known as imperative programming. In addition to raising complications about computational models, programs written in imperative style are susceptible to bugs that cannot occur in functional programs. For example, recall the iterative factorial program from 1.2.1: (define (factorial n) (define (iter product counter) (if (> counter n) product (iter (* counter product) (+ counter 1)))) (iter 1 1)) Instead of passing arguments in the internal iterative loop, we could adopt a more imperative style by using explicit assignment to update the values of the variables product and counter: (define (factorial n) (let ((product 1) (counter 1)) (define (iter) (if (> counter n) product (begin (set!

Instead, ML includes a type-inferencing mechanism that uses information in the environment to deduce the data types for newly defined procedures. 201 Similarly in physics, when we observe a moving particle, we say that the position (state) of the particle is changing. However, from the perspective of the particle’s world line in space-time there is no change involved. 202 John Backus, the inventor of Fortran, gave high visibility to functional programming when he was awarded the ACM Turing award in 1978. His acceptance speech (Backus 1978) strongly advocated the functional approach. A good overview of functional programming is given in Henderson 1980 and in Darlington et al. 1982. 203 Observe that, for any two streams, there is in general more than one acceptable order of interleaving. Thus, technically, “merge” is a relation rather than a function—the answer is not a deterministic function of the inputs.

pages: 754 words: 48,930

Programming in Scala by Martin Odersky, Lex Spoon, Bill Venners

But it can apply its strengths even more when used for building large systems and frameworks of reusable components. Technically, Scala is a blend of object-oriented and functional programming concepts in a statically typed language. The fusion of object-oriented and functional programming shows up in many different aspects of Scala; it is probably more pervasive than in any other widely used language. The two programming styles have complementary strengths when it comes to scalability. Scala’s functional programming constructs make it easy to build interesting things quickly from simple parts. Its object-oriented constructs make it easy to structure larger systems and to adapt them to new demands.

Scala is functional In addition to being a pure object-oriented language, Scala is also a fullblown functional language. The ideas of functional programming are older than (electronic) computers. Their foundation was laid in Alonzo Church’s lambda calculus, which he developed in the 1930s. The first functional programming language was Lisp, which dates from the late 50s. Other popular 7 Kay, “The Early History of Smalltalk.” [Kay96] Cover · Overview · Contents · Discuss · Suggest · Glossary · Index 46 Section 1.2 Chapter 1 · A Scalable Language functional languages are Scheme, SML, Erlang, Haskell, OCaml, and F#. For a long time, functional programming has been a bit on the sidelines, popular in academia, but not that widely used in industry.

Scalability is influenced by many factors, ranging from syntax details to component abstraction constructs. If we were forced to name just one aspect of Scala that helps scalability, though, we’d pick its combination of object-oriented and functional programming (well, we cheated, that’s really two aspects, but they are intertwined). Scala goes further than all other well-known languages in fusing objectoriented and functional programming into a uniform language design. For instance, where other languages might have objects and functions as two different concepts, in Scala a function value is an object. Function types are classes that can be inherited by subclasses.

pages: 1,076 words: 67,364

Haskell Programming: From First Principles by Christopher Allen, Julie Moronuki

Lambda calculus is your foundation, because Haskell is a pure functional programming language. 1.2 What is functional programming? Functional programming is a computer programming paradigm that relies on functions modeled on mathematical functions. The essence of functional programming is that programs are a combination of expressions. Expressions include concrete values, variables, and also functions. Functions have a more speciﬁc deﬁnition: they are expressions that are applied to an argument or input, and once applied, can be reduced or evaluated. In Haskell, and in functional programming more generally, functions are ﬁrst-class: they can be used as values or passed as arguments, or inputs, to yet more functions.

Why Haskell If you are new to programming entirely, Haskell is a great ﬁrst language. You may have noticed the trend of “Functional Programming in [Imperative Language]” books and tutorials and learning Haskell gets right to the heart of what functional programming is. Languages such as Java are gradually adopting functional concepts, but most such languages were not designed to be functional languages. We would not encourage you to learn Haskell as an only language, but because Haskell is a pure functional language, it is a fertile environment for mastering functional programming. That way of thinking and problem solving is useful, no matter what other languages you might know or learn.

In Haskell, and in functional programming more generally, functions are ﬁrst-class: they can be used as values or passed as arguments, or inputs, to yet more functions. We’ll deﬁne these terms more carefully as we progress through the chapter. Functional programming languages are all based on the lambda calculus. Some languages in this general category incorporate features into the language that aren’t translatable into lambda expressions. Haskell is a pure functional language, because it does not. We’ll address this notion of purity more later in the book, but it isn’t a judgment of the moral worth of other languages. The word purity in functional programming is sometimes also used to mean what is more properly called referential transparency. Referential CHAPTER 1.

pages: 519 words: 102,669

Programming Collective Intelligence by Toby Segaran

To activate frequency scoring in your results, change the weights line in getscoredlist to read: weights=[(1.0,self.frequencyscore(rows))] Now you can try another search and see how well this works as a scoring metric: >>reload(searchengine) >> e=searchengine.searcher('searchindex.db') >> e.query('functional programming') 1.000000 http://kiwitobes.com/wiki/Functional_programming.html 0.262476 http://kiwitobes.com/wiki/Categorical_list_of_programming_languages.html 0.062310 http://kiwitobes.com/wiki/Programming_language.html 0.043976 http://kiwitobes.com/wiki/Lisp_programming_language.html 0.036394 http://kiwitobes.com/wiki/Programming_paradigm.html ... This returns the page on "Functional programming" in first place, followed by several other relevant pages. Notice that "Functional programming" scored four times better than the result directly below it.

To see what the results look like using only the location score, change the weights line to this: weights=[(1.0,self.locationscore(rows))] Now try the query again in your interpreter: >>reload(searchengine) >> e=searchengine.searcher('searchindex.db') >> e.query('functional programming') You'll notice that "Functional programming" is still the winner, but the other top results are now examples of functional programming languages. The previous search returned results in which the words were mentioned several times, but these tended to be discussions about programming languages in general. With this search, however, the presence of the words in the opening sentence (e.g., "Haskell is a standardized pure functional programming language") gave them a much higher score. It's important to realize that neither one of the metrics shown so far is better in every case.

Add this method to the searcher class: def pagerankscore(self,rows): pageranks=dict([(row[0],self.con.execute('select score from pagerank where urlid=%d' % row[0]).fetchone( )[0]) for row in rows]) maxrank=max(pageranks.values( )) normalizedscores=dict([(u,float(l)/maxrank) for (u,l) in pageranks.items( )]) return normalizedscores Once again, you should modify the weights list to include PageRank. For example, try: weights=[(1.0,self.locationscore(rows)), (1.0,self.frequencyscore(rows)), (1.0,self.pagerankscore(rows))] The results for your searches will take into account content and ranking scores. The results for "Functional programming" now look even better: 2.318146 http://kiwitobes.com/wiki/Functional_programming.html 1.074506 http://kiwitobes.com/wiki/Programming_language.html 0.517633 http://kiwitobes.com/wiki/Categorical_list_of_programming_languages.html 0.439568 http://kiwitobes.com/wiki/Programming_paradigm.html 0.426817http://kiwitobes.com/wiki/Lisp_programming_language.html The value of the PageRank score is a little harder to see with this closed, tightly controlled set of documents, which likely contains fewer useless pages or pages intended solely to get attention than you'd find on the Web.

Software Design for Flexibility by Chris Hanson, Gerald Sussman

But this is only the start. In chapter 5 we will transcend this embedding strategy, using the powerful idea of metalinguistic abstraction. 1 The generality of the domain model is an example of “Postel's law”—see page 3. 2 There are some notable exceptions: the functional programming extensions introduced by Java 8 directly capture useful combinations. Functional programming languages, such as Lisp and Haskell, have libraries of useful combination mechanisms. 3 Here things are simple, but in complex programs with many internal procedures, descriptive names can make things easier to read and understand. In MIT/GNU Scheme there is a minor advantage to naming the procedure being returned here, because the debugger can show this name for a procedure that would otherwise be anonymous. 4 Documentation of hash table procedures in MIT/GNU Scheme can be found in [51]. 5 We thank Guy L.

For example, write-line changes the display by printing something to the display. 11 It is another cultural convention that we terminate the name of a procedure that has “side effects” with an exclamation point (!). This warns the reader that changing the order of effects may change the results of running the program. 12 The discipline of programming without assignments is called functional programming. Functional programs are generally easier to understand and have fewer bugs than imperative programs. 13 This terminology dates back to the ACTOR framework [58] and the Smalltalk programming language [46]. References [1]Harold Abelson and Gerald Jay Sussman with Julie Sussman, Structure and Interpretation of Computer Programs (2nd ed.).

A number of early programming language designs in effect made a design commitment to reflect the style of hardware organization called the Harvard architecture: the code is here, the data is there, and the job of the code is to massage the data. But an inflexible, arm's-length separation between code and data turns out to be a significant limitation on program organization. Well before the end of the twentieth century, we learned from functional programming languages (such as ML, Scheme, and Haskell) and from object-oriented programming languages (such as Simula, Smalltalk, C++, and Java) that there are advantages to being able to treat code as data, to treat data as code, and to bundle smallish amounts of code and related data together rather than organizing code and data separately as monolithic chunks.

Introducing Elixir by Simon St.Laurent, J. David Eisenberg

on .4 iti n 1 Ed sio d er 2n rs V Co ve Introducing Elixir GETTING STARTED IN FUNCTIONAL PROGRAMMING Simon St. Laurent & J. David Eisenberg SECOND EDITION Introducing Elixir Getting Started in Functional Programming Simon St.Laurent and J. David Eisenberg Beijing Boston Farnham Sebastopol Tokyo Introducing Elixir by Simon St.Laurent and J. David Eisenberg Copyright © 2017 Simon St.Laurent and J. David Eisenberg. All rights reserved. Printed in the United States of America. Published by O’Reilly Media, Inc., 1005 Gravenstein Highway North, Sebastopol, CA 95472. O’Reilly books may be purchased for educational, business, or sales promotional use.

Who This Book Is For This book is mostly for people who’ve been programming in other languages but want to look around. Maybe you’re being very practical, and a distributed model, with its resulting scale and resilience advantages, appeals to you. Maybe you want to see what this “functional programming” stuff is all about. Or maybe you’re just going for a hike, taking your mind to a new place. We suspect that functional programming is more approachable before you’ve learned to program in other paradigms. However, getting started in Elixir—sometimes even just installing it—requires a fair amount of computing skill. If you’re a complete new‐ comer to programming, welcome, but there will be a few challenges along the way.

What This Book Will Do For You You’ll learn to write simple Elixir programs. You’ll understand why Elixir makes it easier to build resilient programs that can scale up and down with ease. You’ll be able to read other Elixir resources that assume a fair amount of experience and make sense of them. In more theoretical terms, you’ll get to know functional programming. You’ll learn how to design programs around message passing and recursion, creating processoriented programs focused more on data flow. Most importantly, the gates to concurrent application development will be opened. Though this introduction only gets you started using the incredible powers of the Open Telecom Platform (OTP), that foundation can take you to amazing places.

pages: 214 words: 31,751

Software Engineering at Google: Lessons Learned From Programming Over Time by Titus Winters, Tom Manshreck, Hyrum Wright

Since the build system now has full control over what tools are being run when, it can make much stronger guarantees that allow it to be far more efficient while still guaranteeing correctness. A Functional Perspective It’s easy to make an analogy between artifact-based build systems and functional programming. Traditional imperative programming languages (e.g. Java, C, and Python) specify lists of statements to be executed one after another, in the same way that task-based build systems let programmers define a series of steps to execute. Functional programming languages (e.g. Haskell and ML), in contrast, are structured more like a series of mathematical equations. In functional languages, the programmer describes a computation to perform, but leaves the details of when and exactly how that computation is executed to the compiler.

This maps to the idea of declaring a manifest in an artifact-based build system and letting the system figure out how to execute the build. Many problems cannot be easily expressed using functional programming, but the ones that do benefit greatly from it: the language is often able to trivially parallelize such programs and make strong guarantees about their correctness that would be impossible in an imperative language. The easiest problems to express using functional programming are the ones that simply involve transforming one piece of data into another using a series of rules or functions. And that’s exactly what a build system is: the whole system is effectively a mathematical function that takes source files (and tools like the compiler) as inputs and produces binaries as outputs.

And that’s exactly what a build system is: the whole system is effectively a mathematical function that takes source files (and tools like the compiler) as inputs and produces binaries as outputs. So it’s not surprising that it works well to base a build system around the tenants of functional programming. Getting Concrete with Bazel Bazel is the open-source version of Google’s internal build tool, Blaze, and is a good example of an artifact-based build system. Here’s what a buildfile (normally named BUILD) looks like in Bazel: java_binary( name = "MyBinary", srcs = ["MyBinary.java"], deps = [ ":mylib", ], ) java_library( name = "mylib", srcs = ["MyLibrary.java", "MyHelper.java"], visibility = ["//java/com/example/myproduct:__subpackages__"], deps = [ "//java/com/example/common", "//java/com/example/myproduct/otherlib", "@com_google_common_guava_guava//jar", ], ) In Bazel, BUILD files define targets - the two types of targets here are java_binary and java_library.

pages: 292 words: 81,699

More Joel on Software by Joel Spolsky

Now, I freely admit that programming with pointers is not needed in 90% of the code written today, and in fact, it’s downright dangerous in production code. OK. That’s fine. And functional programming is just not used much in practice. Agreed. But it’s still important for some of the most exciting programming jobs. Without pointers, for example, you’d never be able to work on the Linux kernel. You can’t understand a line of code in Linux, or, indeed, any operating system, without really understanding pointers. Without understanding functional programming, you can’t invent MapReduce, the algorithm that makes Google so massively scalable. The terms “Map” and “Reduce” come from Lisp and functional programming. MapReduce is, in retrospect, obvious to anyone who remembers from their 6.001-equivalent programming class that purely 56 More from Joel on Software functional programs have no side effects and are thus trivially parallelizable.

And now you understand something I wrote a while ago where I complained about CS students who are never taught anything but Java: Without understanding functional programming, you can’t invent MapReduce, the algorithm that makes Google so massively scalable. The terms “Map” and “Reduce” come from Lisp and functional programming. MapReduce is, in retrospect, obvious to anyone who remembers from their 6.001-equivalent programming class that purely functional programs have no side effects and are thus trivially parallelizable. The very fact that Google invented MapReduce, and Microsoft didn’t, says something about why Microsoft is still playing catch-up trying to get basic search features to work, while Google has moved on to the next problem: building Skynet^H^H^H^H^H^H, the world’s largest massively parallel supercomputer.

I’ve seen all kinds of figures for dropout rates in CS, and they’re usually between 40% and 70%. The universities tend to see this as a waste; I think it’s just a necessary culling of the people who aren’t going to be happy or successful in programming careers. The other hard course for many young CS students was the course where you learned functional programming, including recursive programming. MIT set the bar very high for these courses, creating a required course (6.001) and a textbook (Abelson and Sussman’s Structure and Interpretation of Computer Programs [The MIT Press, 1996]), which were used at dozens or even hundreds of top CS schools as the de facto introduction to computer science.

pages: 1,065 words: 229,099

Real World Haskell by Bryan O'Sullivan, John Goerzen, Donald Stewart, Donald Bruce Stewart

Novelty Haskell is most likely quite different from any language you’ve ever used before. Compared to the usual set of concepts in a programmer’s mental toolbox, functional programming offers us a profoundly different way to think about software. In Haskell, we deemphasize code that modifies data. Instead, we focus on functions that take immutable values as input and produce new values as output. Given the same inputs, these functions always return the same results. This is a core idea behind functional programming. Along with not modifying data, our Haskell functions usually don’t talk to the external world; we call these functions pure.

On one side, it gave language researchers a stable language in which to experiment with making lazy functional programs run efficiently and on the other side researchers explored how to construct programs using lazy functional techniques, and still others used it as a teaching language. The Modern Era While these basic explorations of the 1990s proceeded, Haskell remained firmly an academic affair. The informal slogan of those inside the community was to “avoid success at all costs.” Few outsiders had heard of the language at all. Indeed, functional programming as a field was quite obscure. During this time, the mainstream programming world experimented with relatively small tweaks, from programming in C, to C++, to Java.

Enjoyment We believe that it is easy to pick up the basics of Haskell programming and that you will be able to successfully write small programs within a matter of hours or days. Since effective programming in Haskell differs greatly from other languages, you should expect that mastering both the language itself and functional programming techniques will require plenty of thought and practice. Harking back to our own days of getting started with Haskell, the good news is that the fun begins early: it’s simply an entertaining challenge to dig into a new language— in which so many commonplace ideas are different or missing—and to figure out how to write simple programs.

pages: 135 words: 31,098

ClojureScript: Up and Running by Stuart Sierra, Luke Vanderhart

However, with only a very slight shift in viewpoint, you can also understand any functional program in terms of the data that it manipulates and how that data flows through the system. Every function takes some data as arguments and returns data when it is complete. Usually, the end goal of a program is not to invoke certain execution paths, but to create, retrieve, or transform data in one form or another. Functions are simply the tool for doing so. In a very real sense, one could say that “data-oriented programing” is a synonym for “functional programming.” Clojure and ClojureScript recognize this, and therefore provide a carefully-designed set of data primitives and composite data structures that are both easy to use and philosophically aligned with basic theories about what data is.

Core JavaScript has a limited number of keywords, concepts, and built-in features. This makes it easy to embed in different environments. It is flexible. Features missing from core JavaScript, such as namespaces or classes, can be added using the language itself. JavaScript functions are first-class. Although JavaScript is not a “functional” programming language in the usual sense, the ability to create and compose functions as values grants it immense power. It’s there. Every web browser has had JavaScript built-in since the mid-1990s. Beyond that, the ease of embedding JavaScript in other applications has led to its inclusion in products as diverse as databases and television set-top boxes.

For example, the number zero, when used in a Boolean expression, is false in JavaScript but true in ClojureScript. See the sidebar on “Truthiness” in Chapter 4. To use a Boolean as a literal, just type one of the special symbols true or false. Functions In ClojureScript (like JavaScript), functions are first-class entities and, as befits a functional programming language, are themselves data. They can be created using the syntax discussed in the previous chapter, and once created can be passed around and added to composite data structures like any other data. Importantly, ClojureScript functions are implemented as plain old JavaScript functions.

Text Analytics With Python: A Practical Real-World Approach to Gaining Actionable Insights From Your Data by Dipanjan Sarkar

This brings us to the end of our discussion on the core constructs for controlling flow of code in Python. The next section covers some core concepts and constructs that are parts of the functional programming paradigm in Python. Functional Programming The functional programming paradigm is a style of programming with origins in lambda calculus. It treats any form of computation purely on the basis of executing and evaluating functions. Python is not a pure functional programming language but does have several constructs that can be used for functional programming. In this section we will talk about several of these constructs, including functions and some advanced concepts like generators, iterators, and comprehensions.

As mentioned, Python is a general-purpose programming language that supports multiple programming paradigms, including the following popular programming paradigms : Object-oriented programming Functional programming Procedural programming Aspect-oriented programming A lot of OOP concepts are present in Python, including classes, objects, data, and methods. Principles like abstraction, encapsulation, inheritance, and polymorphism can also be implemented and exhibited using Python. There are several advanced features in Python, including iterators, generators, list comprehensions, lambda expressions, and several modules like itertools and functools, which provide the ability to write code following the functional programming paradigm. Python was designed keeping in mind the fact that simple and beautiful code is more elegant and easy to use rather than doing premature optimization and writing hard-to-interpret code.

Integrated Development Environments Environment Setup Virtual Environments Python Syntax and Structure Data Structures and Types Numeric Types Strings Lists Sets Dictionaries Tuples Files Miscellaneous Controlling Code Flow Conditional Constructs Looping Constructs Handling Exceptions Functional Programming Functions Recursive Functions Anonymous Functions Iterators Comprehensions Generators The itertools and functools Modules Classes Working with Text String Literals String Operations and Methods Text Analytics Frameworks Summary Chapter 3:​ Processing and Understanding Text Text Tokenization Sentence Tokenization Word Tokenization Text Normalization Cleaning Text Tokenizing Text Removing Special Characters Expanding Contractions Case Conversions Removing Stopwords Correcting Words Stemming Lemmatization Understanding Text Syntax and Structure Installing Necessary Dependencies Important Machine Learning Concepts Parts of Speech (POS) Tagging Shallow Parsing Dependency-based Parsing Constituency-based Parsing Summary Chapter 4:​ Text Classification What Is Text Classification?​

Elixir in Action by Saša Jurić

—Ved Antani, Electronic Arts Outstanding coverage of Elixir’s distributed computing capabilities, with a real-world point of view. —Christopher Bailey, HotelTonight Read this book if you want to think and solve problems in the Elixir way! —Kosmas Chatzimichalis, Mach 7x Functional programming made easy. —Mohsen Mostafa Jokar, Hamshahri Probably the best introduction to Elixir and the Functional Programming. —Amazon customer A good book for experienced programmers who want to learn more about Elixir. —Amazon customer Elixir in Action Second Edition SAŠA JURIĆ MANNING Shelter Island For online information and ordering of this and other Manning books, please visit www.manning.com.

Any experience in development of backend (server-side) systems is welcome. You don’t need to know anything about Erlang, Elixir, or other concurrent platforms. In particular, you don’t need to know anything about functional programming. Elixir is a functional language, and if you come from an OO background, this may scare you a bit. As a long-time OO programmer, I can sincerely tell you not to worry. The underlying functional concepts in Elixir are relatively simple and should be easy to grasp. Of course, functional programming is significantly different from whatever you’ve seen in a typical OO language, and it takes some getting used to. But it’s not rocket science, and if you’re an experienced developer, you should have no problem understanding these concepts.

The people who gave us Elixir and Erlang, including the original inventors, core team members, and contributors, deserve a special mention. Thank you for creating such great products, which make my job easier and more fun. Finally, special thanks to all the members of the Elixir community; this is the nicest and friendliest developer community I’ve ever seen! about this book Elixir is a modern functional programming language for building large-scale scalable, distributed, fault-tolerant systems for the Erlang virtual machine. Although the language is compelling in its own right, arguably its biggest advantage is that it targets the Erlang platform. Erlang was made to help developers deal with the challenge of high availability.

pages: 398 words: 86,855

Bad Data Handbook by Q. Ethan McCallum

For example, you might want to place a new member of the team on one of the infrastructure pieces that is doing well, and should be a model for other pieces, as to give them a good starting place for learning the system. A more senior team member may be more effective on pieces of the infrastructure that are struggling. Immutability: Borrowing an Idea from Functional Programming Considering the examples above, a core element of our strategy was immutability: even though our processing pipeline transformed our data several times over, we never changed (overwrote) the original data. This is an idea we borrowed from functional programming. Consider imperative languages like C, Java, and Python, in which data tends to be mutable. For example, if we want to sort a list, we might call myList.sort().

, Splits, Dividends, and Rescaling–Splits, Dividends, and Rescaling, But First, Let’s Reflect on Graduate School …–But First, Let’s Reflect on Graduate School …, Moving into Government Work–Government Data Is Very Real, Be Inconsistent in Cleaning and Organizing the Data, Data Traceability–Conclusion, Snapshotting, Backing Out Data, Immutability: Borrowing an Idea from Functional Programming–Immutability: Borrowing an Idea from Functional Programming, Social Media: Whose Data Is This Anyway?–Control, Expectations Around Communication and Expression–Update Notification API, aCcountable–aCcountable assumptions about, problems with, Lessons Learned–Lessons Learned cleaning, General Workflow Example, But First, Let’s Reflect on Graduate School …–But First, Let’s Reflect on Graduate School …, Moving into Government Work–Government Data Is Very Real, Be Inconsistent in Cleaning and Organizing the Data empty values in, Field Validation field values not comparable over time, Splits, Dividends, and Rescaling–Splits, Dividends, and Rescaling immutability of, Snapshotting, Immutability: Borrowing an Idea from Functional Programming–Immutability: Borrowing an Idea from Functional Programming ownership of, Social Media: Whose Data Is This Anyway?

–Control, Expectations Around Communication and Expression–Update Notification API, aCcountable–aCcountable assumptions about, problems with, Lessons Learned–Lessons Learned cleaning, General Workflow Example, But First, Let’s Reflect on Graduate School …–But First, Let’s Reflect on Graduate School …, Moving into Government Work–Government Data Is Very Real, Be Inconsistent in Cleaning and Organizing the Data empty values in, Field Validation field values not comparable over time, Splits, Dividends, and Rescaling–Splits, Dividends, and Rescaling immutability of, Snapshotting, Immutability: Borrowing an Idea from Functional Programming–Immutability: Borrowing an Idea from Functional Programming ownership of, Social Media: Whose Data Is This Anyway?–Control removal of, Backing Out Data, Expectations Around Communication and Expression–Update Notification API traceability of, Data Traceability–Conclusion, aCcountable–aCcountable unique identifiers in, changing over time, Whose Ticker Is It Anyway?

pages: 450 words: 569

ANSI Common LISP by Paul Graham

All such operators are marked as "settable" in Appendix D. 22 WELCOME TO LISP You can give any (even) number of arguments to setf. An expression of the form (setf a b c d e f) is equivalent to three separate calls to s e t f in sequence: (setf a b) (setf c d) (setf e f) 2.12 Functional Programming Functional programming means writing programs that work by returning values, instead of by modifying things. It is the dominant paradigm in Lisp. Most built-in Lisp functions are meant to be called for the values they return, not for side-effects. The function remove, for example, takes an object and a list and returns a new list containing everything but that object: > ( s e t f 1st ' ( c a r a t ) ) (CARAT) > (remove 'a 1st) (C R T) Why not just say that remove removes an object from a list?

To remove all the as from a list x, we say: ( s e t f x (remove ' a x ) ) Functional programming means, essentially, avoiding setf and things like it. At first sight it may be difficult to imagine how this is even possible, let alone desirable. How can one build programs just by returning values? 2.13 23 ITERATION It would be inconvenient to do without side-effects entirely. However, as you read further, you may be surprised to discover how few you really need. And the more side-effects you do without, the better off you'll be. One of the most important advantages of functional programming is that it allows interactive testing.

Introduction 1.1. 1.2. 1.3. 1 New Tools 1 New Techniques 3 A New Approach 4 2. Welcome to Lisp 2.1. 2.2. 2.3. 2.4. 2.5. 2.6. 2.7. 2.8. 2.9. 2.10. 2.11. 2.12. 2.13. 2.14. 2.15. 2.16. 7 Form 7 Evaluation 9 Data 10 List Operations 12 Truth 13 Functions 14 Recursion 16 Reading Lisp 17 Input and Output 18 Variables 19 Assignment 21 Functional Programming 22 Iteration 23 Functions as Objects 25 Types 27 Looking Forward 27 3. Lists 3.1. 3.2. 3.3. 3.4. 3.5. 3.6. 3.7. 3.8. 3.9. 3.10. 3.11. 3.12. 3.13. 3.14. 3.15. 3.16. Mapping Functions 40 Trees 40 Understanding Recursion 42 Sets 43 Sequences 45 Stacks 47 Dotted Lists 49 Assoc-lists 51 Example: Shortest Path 51 Garbage 54 4.

pages: 514 words: 111,012

The Art of Monitoring by James Turnbull

We don't really care about the "how"; the database engine takes care of those details. In addition to their declarative nature, functional programming languages try to eliminate all side effects from changing state. In a functional language, when you call a function its output value depends only on the inputs to the function. So if you repeatedly call function f with the same value for argument x, f(x), it will produce the same result every time. This makes functional programs easy to understand, test, and predict. Functional programming languages call functions that operate like this "pure" functions. The best way to get started with Clojure is to understand the basics of its syntax and types.

Additionally, Riemann comes with a lot of helpers and shortcuts that make it easier to write Clojure to do what we need to process our events. Let's learn a bit more about Clojure and help you get started with Riemann. Clojure is a dynamic programming language that targets the Java Virtual Machine. It's a dialect of Lisp and is largely a functional programming language. Functional programming is a programming style that focuses on the evaluation of mathematical functions and steers away from changing state and mutable data. It's highly declarative, meaning you build programs from expressions that describe "what" a program should accomplish rather than "how" it accomplishes things.

Pragmatic.Programming.Erlang.Jul.2007 by Unknown

In Chapter 18, Making a System with OTP, we’ll look at how to make highly reliable systems that have been in round-the-clock operation for years. In Section 16.1, The Road to the Generic Server, on page 292, we’ll talk about techniques for writing servers where the software can be upgraded without taking the server out of service. R OAD M AP In many places we’ll be extolling the virtues of functional programming. Functional programming forbids code with side effects. Side effects and concurrency don’t mix. You can have sequential code with side effects, or you can have code and concurrency that is free from side effects. You have to choose. There is no middle way. Erlang is a language where concurrency belongs to the programming language and not the operating system.

There are loads of programming languages, so why should you learn another? Here are five reasons why you should learn Erlang: • You want to write programs that run faster when you run them on a multicore computer. • You want to write fault-tolerant applications that can be modified without taking them out of service. • You’ve heard about “functional programming” and you’re wondering whether the techniques really work. • You want to use a language that has been battle tested in real large-scale industrial products that has great libraries and an active user community. • You don’t want to wear your fingers out by typing lots of lines of code. Can we do these things?

Surely it couldn’t be that easy. The basic program was simple, and with a few more lines of code, file sharing and encrypted conversations became possible. The programmer started typing.... What’s This All About? It’s about concurrency. It’s about distribution. It’s about fault tolerance. It’s about functional programming. It’s about programming a distributed concurrent system without locks and mutexes but using only pure message passing. It’s about speeding up your programs on multicore CPUs. It’s about writing distributed applications that allow people to interact with each other. It’s about design methods and behaviors for writing fault-tolerant and distributed systems.

pages: 821 words: 178,631

The Rust Programming Language by Steve Klabnik, Carol Nichols

Next, we’ll explore some Rust features that were influenced by functional languages: closures and iterators. 13 FUNCTIONAL LANGUAGE FEATURES: ITERATORS AND CLOSURES Rust’s design has taken inspiration from many existing languages and techniques, and one significant influence is functional programming. Programming in a functional style often includes using functions as values by passing them in arguments, returning them from other functions, assigning them to variables for later execution, and so forth. In this chapter, we won’t debate the issue of what functional programming is or isn’t but will instead discuss some features of Rust that are similar to features in many languages often referred to as functional. More specifically, we’ll cover: Closures, a function-like construct you can store in a variable Iterators, a way of processing a series of elements How to use these two features to improve the I/O project in Chapter 12 The performance of these two features (Spoiler alert: they’re faster than you might think!)

In Chapter 12, we’ll build our own implementation of a subset of functionality from the grep command line tool that searches for text within files. For this, we’ll use many of the concepts we discussed in the previous chapters. Chapter 13 explores closures and iterators: features of Rust that come from functional programming languages. In Chapter 14, we’ll examine Cargo in more depth and talk about best practices for sharing your libraries with others. Chapter 15 discusses smart pointers that the standard library provides and the traits that enable their functionality. In Chapter 16, we’ll walk through different models of concurrent programming and talk about how Rust helps you to program in multiple threads fearlessly.

There are multiple trade-offs to consider in addition to the prevention of bugs. For example, in cases where you’re using large data structures, mutating an instance in place may be faster than copying and returning newly allocated instances. With smaller data structures, creating new instances and writing in a more functional programming style may be easier to think through, so lower performance might be a worthwhile penalty for gaining that clarity. Differences Between Variables and Constants Being unable to change the value of a variable might have reminded you of another programming concept that most other languages have: constants.

pages: 688 words: 107,867

Python Data Analytics: With Pandas, NumPy, and Matplotlib by Fabio Nelli

.>>> items = [1,2,3,4,5] >>> for item in items: ... print(item + 1) ... 2 3 4 5 6 Functional Programming The for-in loop shown in the previous example is very similar to loops found in other programming languages. But actually, if you want to be a “Python” developer, you have to avoid using explicit loops. Python offers alternative approaches, specifying programming techniques such as functional programming (expression-oriented programming). The tools that Python provides to develop functional programming comprise a series of functions: map(function, list) filter(function, list) reduce(function, list) lambda list comprehension The for loop that you have just seen has a specific purpose, which is to apply an operation on each item and then somehow gather the result.

.>>> list(filter((lambda x: x < 4), items)) [1, 2, 3] >>> from functools import reduce >>> reduce((lambda x,y: x/y), items) 0.008333333333333333 Both of these functions implement other types by using the for loop. They replace these cycles and their functionality, which can be alternatively expressed with simple functions. That is what constitutes functional programming. The final concept of functional programming is list comprehension. This concept is used to build lists in a very natural and simple way, referring to them in a manner similar to how mathematicians describe datasets. The values in the sequence are defined through a particular function or operation.>>> S = [x**2 for x in range(5)] >>> S [0, 1, 4, 9, 16] Indentation A peculiarity for those coming from other programming languages is the role that indentation plays.

pages: 559 words: 130,949

Learn You a Haskell for Great Good!: A Beginner's Guide by Miran Lipovaca

They’re a great resource for Haskell newbies. So, What's Haskell? Haskell is a purely functional programming language. In imperative programming languages, you give the computer a sequence of tasks, which it then executes. While executing them, the computer can change state. For instance, you can set the variable a to 5 and then do some stuff that might change the value of a. There are also flow-control structures for executing instructions several times, such as for and while loops. Purely functional programming is different. You don’t tell the computer what to do—you tell it what stuff is. For instance, you can tell the computer that the factorial of a number is the product of every integer from 1 to that number or that the sum of a list of numbers is the first number plus the sum of the remaining numbers.

For instance, you can tell the computer that the factorial of a number is the product of every integer from 1 to that number or that the sum of a list of numbers is the first number plus the sum of the remaining numbers. You can express both of these operations as functions. In functional programming, you can’t set a variable to one value and then set it to something else later on. If you say a is 5, you can’t just change your mind and say it’s something else. After all, you said it was 5. (What are you, some kind of liar?) In purely functional languages, a function has no side effects. The only thing a function can do is calculate something and return the result.

Now, we just need to modify the function to only output the triangles whose perimeter equals 24: ghci> let rightTriangles' = [ (a,b,c) | c <- [1..10], a <- [1..c], b <- [1..a], a^2 + b^2 == c^2, a+b+c == 24] ghci> rightTriangles' [(6,8,10)] And there’s our answer! This is a common pattern in functional programming: you start with a certain set of candidate solutions, and successively apply transformations and filters to them until you’ve narrowed the possibilities down to the one solution (or several solutions) that you’re after. Chapter 2. Believe the Type One of Haskell’s greatest strengths is its powerful type system.

pages: 239 words: 64,812

Geek Sublime: The Beauty of Code, the Code of Beauty by Vikram Chandra

The next great hope for more stable, bug-free software is functional programming, which is actually the oldest paradigm in computing—it uses the algebraic techniques of function evaluation used by the creators of the first computers. In functional programming, all computation is expressed as the evaluation of expressions; the radical simplicity of thinking about programming as only giving input to functions that produce outputs promotes legibility and predictability. There is again the same fervent proselytizing about functional programming that I remember from the early days of OOP, the same conviction that this time we’ve discovered the magic key to the kingdom.

The poet Kshemendra—Abhinavagupta’s student—left this advice: A poet should learn with his eyes the forms of leaves he should know how to make people laugh when they are together he should get to see what they are really like he should know about oceans and mountains in themselves and the sun and the moon and the stars his mind should enter into the seasons he should go among many people in many places and learn their languages10 I have a sabbatical coming up. My plan is: (1) write fiction; (2) learn a functional programming language; and (3) learn Sanskrit. In Red Earth and Pouring Rain one of the characters builds a gigantic knot. “I made the knot,” he says. I made it of twine, string, leather thongs, strands of fibrous materials from plants, pieces of cloth, the guts of animals, lengths of steel and copper, fine meshes of gold, silver beaten thin into filament, cords from distant cities, women’s hair, goats’ beards; I used butter and oil; I slid things around each other and entangled them, I pressed them together until they knew each other so intimately that they forgot they were ever separate, and I tightened them against each other until they squealed and groaned in agony; and finally, when I had finished, I sat cross-legged next to the knot, sprinkled water in a circle around me and whispered the spells that make things enigmatic, the chants of profundity and intricacy.

pages: 190 words: 52,865

Full Stack Web Development With Backbone.js by Patrick Mulder

With NVM, you can easily switch between versions of Node.js. 157 Getting Functional with Underscore.js Because JavaScript in its old standard didn’t have helpers for dealing with enumerators, Underscore.js was born. Underscore.js provides many nifty JavaScript shortcuts and is also a core dependency of Backbone.js. Underscore.js derives many ideas from func‐ tional programming. In functional programming, we can easily extract meta information from data struc‐ tures, or chain operations on data structures independent from the data itself. This flexibility is achieved by passing functions as arguments to other functions, often under the concept of higher-level functions. The main goal of the Underscore.js library is to provide a set of abstractions to transform and aggregate data structures.

After loading the library, we obtain a helper to the global namespace of the browser window. To get a feeling of what the shortcut can do, we can look at some examples. Due to the success of Underscore.js, there are a number of deriva‐ tives from the original library. First, in underscore-contrib, a lot more ideas from functional programming are made possible in JavaScript. Another variation can be found in underscore.string. This library provides a number of default string transformations Last, there is underscore-cli, which provides helpers to transform JSON from the command line. Collections and Arrays Some of the most important helpers from Underscore.js are improvements in dealing with collections.

pages: 818 words: 153,952

C++ Concurrency in Action: Practical Multithreading by Anthony Williams

Using synchronization of operations to simplify code Using the synchronization facilities described so far in this chapter as building blocks allows you to focus on the operations that need synchronizing rather than the mechanics. One way this can help simplify your code is that it accommodates a much more functional (in the sense of functional programming) approach to programming concurrency. Rather than sharing data directly between threads, each task can be provided with the data it needs, and the result can be disseminated to any other threads that need it through the use of futures. 4.4.1. Functional programming with futures The term functional programming (FP) refers to a style of programming where the result of a function call depends solely on the parameters to that function and doesn’t depend on any external state.

Making (std::)promises 4.2.4. Saving an exception for the future 4.2.5. Waiting from multiple threads 4.3. Waiting with a time limit 4.3.1. Clocks 4.3.2. Durations 4.3.3. Time points 4.3.4. Functions that accept timeouts 4.4. Using synchronization of operations to simplify code 4.4.1. Functional programming with futures 4.4.2. Synchronizing operations with message passing 4.5. Summary Chapter 5. The C++ memory model and operations on atomic types 5.1. Memory model basics 5.1.1. Objects and memory locations 5.1.2. Objects, memory locations, and concurrency 5.1.3. Modification orders 5.2.

This is such a powerful simplification that programming languages such as Haskell,[2] where all functions are pure by default, are becoming increasingly popular for programming concurrent systems. Because most things are pure, the impure functions that actually do modify the shared state stand out all the more, and it’s therefore easier to reason about how they fit into the overall structure of the application. 2 See http://www.haskell.org/. The benefits of functional programming aren’t limited to those languages where it’s the default paradigm, however. C++ is a multiparadigm language, and it’s entirely possible to write programs in the FP style. This is even easier in C++11 than it was in C++98, with the advent of lambda functions (see appendix A, section A.6), the incorporation of std::bind from Boost and TR1, and the introduction of automatic type deduction for variables (see appendix A, section A.7).

pages: 489 words: 117,470

Programming in Lua, Fourth Edition by Roberto Ierusalimschy

Instead of a one-size-fits-all solution, Lua offers us a meta-mechanism, so that we can tailor our environment for our specific security needs. (Real sandboxes do more than protecting external files. We will return to this subject in the section called “Sandboxing”.) A Taste of Functional Programming To give a more concrete example of functional programming, in this section we will develop a simple system for geometric regions.[11] The goal is to develop a system to represent geometric regions, where a region is a set of points. We want to be able to represent all kinds of shapes and to combine and modify shapes in several ways (rotation, translation, union, etc.).

The External World The Simple I/O Model The Complete I/O Model Other Operations on Files Other System Calls 8. Filling some Gaps Local Variables and Blocks Control Structures break, return, and goto II. Real Programming 9. Closures Functions as First-Class Values Non-Global Functions Lexical Scoping A Taste of Functional Programming 10. Pattern Matching The Pattern-Matching Functions Patterns Captures Replacements Tricks of the Trade 11. Interlude: Most Frequent Words 12. Date and Time The Function os.time The Function os.date Date–Time Manipulation 13. Bits and Bytes Bitwise Operators Unsigned Integers Packing and Unpacking Binary Data Binary files 14.

Together, these two features give great flexibility to the language; for instance, a program can redefine a function to add new functionality or erase a function to create a secure environment when running a piece of untrusted code (such as code received through a network). More importantly, these features allow us to apply in Lua many powerful programming techniques from the functional-language world. Even if you have no interest at all in functional programming, it is worth learning a little about how to explore these techniques, because they can make your programs smaller and simpler. Functions as First-Class Values As we just saw, functions in Lua are first-class values. The following example illustrates what that means: a = {p = print} -- 'a.p' refers to the 'print' function a.p("Hello World") --> Hello World print = math.sin -- 'print' now refers to the sine function a.p(print(1)) --> 0.8414709848079 math.sin = a.p -- 'sin' now refers to the print function math.sin(10, 20) --> 10 20 If functions are values, are there expressions that create functions?

pages: 262 words: 60,248

Python Tricks: The Book by Dan Bader

You can assign them to variables, store them in data structures, pass them as arguments to other functions, and even return them as values from other functions. Grokking these concepts intuitively will make understanding advanced features in Python like lambdas and decorators much easier. It also puts you on a path towards functional programming techniques. Over the next few pages I’ll guide you through a number of examples to help you develop this intuitive understanding. The examples will build on top of each other, so you might want to read them in sequence and even to try out some of them in a Python interpreter session as you go along.

It allows you to abstract away and pass around behavior in your programs. In this example, the greet function stays the same but you can influence its output by passing in different greeting behaviors. Functions that can accept other functions as arguments are also called higher-order functions. They are a necessity for the functional programming style. The classical example for higher-order functions in Python is the built-in map function. It takes a function object and an iterable, and then calls the function on each element in the iterable, yielding the results as it goes along. Here’s how you might format a sequence of greetings all at once by mapping the bark function to them: >>> list(map(bark, ['hello', 'hey', 'hi'])) ['HELLO!'

Functions Can Capture Local State You just saw how functions can contain inner functions, and that it’s even possible to return these (otherwise hidden) inner functions from the parent function. Best put on your seat belt now because it’s going to get a little crazier still—we’re about to enter even deeper functional programming territory. (You had that coffee break, right?) Not only can functions return other functions, these inner functions can also capture and carry some of the parent function’s state with them. Well, what does that mean? I’m going to slightly rewrite the previous get_speak_func example to illustrate this.

pages: 692 words: 95,244

Speaking JavaScript: An In-Depth Guide for Programmers by Axel Rauschmayer

On the other hand, it has several powerful features that allow you to work around these problems. In other languages, you learn language features. In JavaScript, you often learn patterns instead. Given its influences, it is no surprise that JavaScript enables a programming style that is a mixture of functional programming (higher-order functions; built-in map, reduce, etc.) and object-oriented programming (objects, inheritance). Syntax This section explains basic syntactic principles of JavaScript. An Overview of the Syntax A few examples of syntax: // Two slashes start single-line comments var x; // declaring a variable x = 3 + y; // assigning a value to the variable `x` foo(x, y); // calling function `foo` with parameters `x` and `y` obj.bar(3); // calling method `bar` of object `obj` // A conditional statement if (x === 0) { // Is `x` equal to zero?

I’ve written fair amounts of code in several programming languages from different paradigms. Therefore, I’m well aware that JavaScript isn’t the pinnacle of elegance. However, it is a very flexible language, has a reasonably elegant core, and enables you to use a mixture of object-oriented programming and functional programming. Language compatibility between JavaScript engines used to be a problem, but isn’t anymore, partly thanks to the test262 suite that checks engines for conformance to the ECMAScript specification. In contrast, browser and DOM differences are still a challenge. That’s why it is normally best to rely on frameworks for hiding those differences.

For example, you can freely add and remove properties (fields) of objects after they have been created. And you can directly create objects, without creating an object factory (e.g., a class) first. It’s dynamically typed Variables and object properties can always hold values of any type. It’s functional and object-oriented JavaScript supports two programming language paradigms: functional programming (first-class functions, closures, partial application via bind(), built-in map() and reduce() for arrays, etc.) and object-oriented programming (mutable state, objects, inheritance, etc.). It fails silently JavaScript did not have exception handling until ECMAScript 3. That explains why the language so often fails silently and automatically converts the values of arguments and operands: it initially couldn’t throw exceptions.

Reactive Messaging Patterns With the Actor Model: Applications and Integration in Scala and Akka by Vaughn Vernon

It also doesn’t mean that sequential processes can’t execute other sequential processes because we’ve had that ability even in the mainstream for several decades. Yet, those newly spawned sequential processes are still static and capable of doing only what their build generated them to do. On the other hand, the Actor model can employ both sequential and functional programming techniques in a highly dynamic environment, where actors come and go as needed, and can even alter their behavior on the fly as the domain or operational environment demands. That is, reactive systems are not only concurrent and distributed but also elastic, dynamic, responsive, and resilient.

Since you don’t get Scala for free with Gradle, you will have to drag in the Scala compiler, which you don’t have to do when you use sbt. Still, that’s just a few lines of code. Programming with Scala If you work in Java and you haven’t yet learned Scala, you should. Of all JVM languages other than Java itself, Scala has the greatest uptake. With a mixture of unobtrusive object-oriented and functional programming facilities, it’s hard to imagine not finding the tools you want and need to code better and faster. Back in the early to late 1980s, I was programming in C and C++ and had also spent a bit of time with Smalltalk. I liked Smalltalk a lot, and I kept trying to find ways to make C++ more like Smalltalk.

I purposely avoid an exhaustive treatment on the Scala programming language. I do provide a simple tutorial on some of the Scala basics, preparing you to read code in this book, and even get started programming in Scala yourself. If you are already familiar with an object-oriented language such as Java or C# and possibly have even studied a bit about functional programming or used a functional language, you should find Scala pretty easy to pick up. If you want to learn Scala quickly, I recommend getting the book Atomic Scala by Bruce Eckel and Dianne Marsh [Atomic-Scala]. Others find Scala for the Impatient [Horstmann] to be “the best compact introduction to Scala,” including Scala’s creator, Martin Odersky.

pages: 474 words: 91,222

Effective STL: 50 Specific Ways to Improve Your Use of the Standard Template Library by Scott Meyers

To see what I mean, here is the same statement, but with all the function names replaced by fn, each n corresponding to one of the functions: v.f1(f2(f3(v.f4(), v.f5(), f6(f7(), y)).f8(), v.f9(), f6(f10(), x)), v.f9()); This looks unnaturally complicated, because I’ve removed the indentation present in the original example, but I think it’s safe to say that any statement involving twelve function calls to ten different functions would be considered excessive by most C++ software developers. Programmers weaned on functional languages such as Scheme might feel differently, however, and my experience has been that the majority of programmers who view the original code without raising an eyebrow have a strong functional programming background. Most C++ programmers lack this background, so unless your colleagues are versed in the ways of deeply nested function calls, code like the erase call above is almost sure to confound the next person who is forced to make sense of what you have written. The second drawback of the code is the significant STL background needed to understand it.

As I noted, some C++ programmers think nothing of the code in this Item. If that’s typical in the environment in which you work and you expect it to be typical in the future, feel free to unleash your most advanced STL programming inclinations. However, if your colleagues are less comfortable with a functional programming style and are less experienced with the STL, scale back your ambitions and write something more along the lines of the two-statement alternative I showed earlier. It’s a software engineering truism that code is read more often than it is written. Equally well established is that software spends far more time in maintenance than it does in development.

pages: 408 words: 85,118

Python for Finance by Yuxing Yan

Python is available for all major operating systems such as Windows, Linux/Unix, OS/2, Mac, and Amiga, among others. Thirdly, Python is suitable for Big Data. Dasgupta (2013) argues that R and Python are two of the most popular open source programming languages for data analysis. Compared with R, Python is generally a better overall language, especially when you consider its blend of functional programming with object orientation. Combined with Scipy/Numpy, Matplotlib, and Statsmodel, it provides a powerful tool. In this book, we will discuss a module called Pandas when we deal with financial data. Fourthly, there are many useful modules for Python, such as toolboxes in MATLAB and packages in R.

The second way to input values is based on key words. The advantage of this so-called key word method is that the order of input values does not play a role anymore. This could reduce our careless mistakes because we don't have to remember the input order when we call a function. This is especially true when we are dealing with many functions (programs) written by different developers/authors: >>>pv_f(r=0.1,fv=100,n=1) 90.9090909090909 >>>pv_f(n=1,fv=100,r=0.1) 90.9090909090909 • The third way is the combination of the preceding two methods: ordered input first and then inputs with keywords, as shown in the following code: >>>pv=pv_f(100,r=0.1,n=1) >>>pv2=pv_f(100,n=1,r=0.1) A word of caution is that the third method is the ordered inputs first, then input(s) with key words, and not the other way around.

Note that the return value is a1 instead of x. Click on Run and then click on Run from module F5; you will see that the following line appears: >>>===========RESTART ================== 7. We could test this program by entering any value. Here is an example: >>>CND(1) 0.31938153 8. Repeat the previous step until we complete this CND() function (program) as shown in the following code: from math import * def CND(X): [ 73 ] 13 Lines of Python to Price a Call Option (a1,a2,a3,a4,a5)=(0.31938153,-0.356563782,1.781477937, -1.821255978,1.330274429) L = abs(X) K=1.0/(1.0+0.2316419*L) w=1.0-1.0/sqrt(2*pi)*exp(-L*L/2.)*(a1*K+a2*K*K+a3*pow(K,3) +a4*pow(K,4)+a5*pow(K,5)) if X<0: w = 1.0-w return w 9.

pages: 246 words: 16,997

Financial Modelling in Python by Shayne Fletcher, Christopher Gardner

pages: 508 words: 120,339

Working Effectively With Legacy Code by Michael Feathers

This is an ideal candidate for a “but that would be stupid” rule. If we know when we start to look at the CppClass that we have been given a list that won’t change, our reasoning is much easier. In general, programming gets easier as we narrow effects in a program. We need to know less to understand a piece of code. At the extreme, we end up with functional programming in languages such as Scheme and Haskell. Programs can actually be very easy to understand in those languages, but those languages aren’t in widespread use. Regardless, in OO languages, restricting effects can make testing much easier, and there aren’t any hurdles to doing it. Simplifying Effect Sketches This book is about making legacy code easier to work with, so there is a sort of “spilt milk” quality to a lot of the examples.

The title of this chapter is a bit provocative. We can make safe changes in any language, but some languages make change easier than others. Even though object orientation has pretty much pervaded the industry, there are many other languages and ways of programming. There are rule-based languages, functional programming languages, constraint-based programming languages—the list goes on. But of all of these, none are as widespread as the plain old procedural languages, such as C, COBOL, FORTRAN, Pascal, and BASIC. Procedural languages are especially challenging in a legacy environment. It’s important to get code under test before modifying it, but the number of things you can do to introduce unit tests in procedural languages is pretty small.

It’s important to get code under test before modifying it, but the number of things you can do to introduce unit tests in procedural languages is pretty small. Often the easiest thing to do is think really hard, patch the system, and hope that your changes were right. This testing dilemma is pandemic in procedural legacy code. Procedural languages often just don’t have the seams that OO (and many functional) programming languages do. Savvy developers can work past this by managing their dependencies carefully (there is a lot of great code written in C, for instance), but it is also easy to end up with a real snarl that is hard to change incrementally and verifiably. Because breaking dependencies in procedural code is so hard, often the best strategy is to try to get a large chunk of the code under test before doing anything else and then use those tests to get some feedback while developing.

pages: 58 words: 12,386

Big Data Glossary by Pete Warden

There is a cost to this approach, though. Writing distributed data handling code is tricky and involves tradeoffs between speed, scalability, fault tolerance, and traditional database goals like atomicity and consistency. MapReduce MapReduce is an algorithm design pattern that originated in the functional programming world. It consists of three steps. First, you write a mapper function or script that goes through your input data and outputs a series of keys and values to use in calculating the results. The keys are used to cluster together bits of data that will be needed to calculate a single output result.

pages: 1,237 words: 227,370

Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems by Martin Kleppmann

MapReduce is neither a declarative query language nor a fully imperative query API, but somewhere in between: the logic of the query is expressed with snippets of code, which are called repeatedly by the processing framework. It is based on the map (also known as collect) and reduce (also known as fold or inject) functions that exist in many functional programming languages. To give an example, imagine you are a marine biologist, and you add an observation record to your database every time you see animals in the ocean. Now you want to generate a report saying how many sharks you have sighted per month. In PostgreSQL you might express that query like this: SELECT date_trunc('month', observation_timestamp) AS observation_month, sum(num_animals) AS total_animals FROM observations WHERE family = 'Sharks' GROUP BY observation_month; The date_trunc('month', timestamp) function determines the calendar month containing timestamp, and returns another timestamp representing the beginning of that month.

In principle, one type of processing can be emulated on top of the other, although the performance characteristics vary: for example, microbatching may perform poorly on hopping or sliding windows [6]. Maintaining derived state Batch processing has a quite strong functional flavor (even if the code is not written in a functional programming language): it encourages deterministic, pure functions whose output depends only on the input and which have no side effects other than the explicit outputs, treating inputs as immutable and outputs as append-only. Stream processing is similar, but it extends operators to allow managed, fault-tolerant state (see “Rebuilding state after a failure”).

This style of deployment is convenient, as servers can be added or removed at will, but the state has to go somewhere: typically, a database. The trend has been to keep stateless application logic separate from state management (databases): not putting application logic in the database and not putting persistent state in the application [36]. As people in the functional programming community like to joke, “We believe in the separation of Church and state” [37].i In this typical web application model, the database acts as a kind of mutable shared variable that can be accessed synchronously over the network. The application can read and update the variable, and the database takes care of making it durable, providing some concurrency control and fault tolerance.

Python Web Development With Django by Jeff Forcier

If we had set default to datetime.date.today()—note the parentheses—the function would be called at the time the model was defined, which is not what we want. Instead, we pass the function object; Django is aware of this and calls the function at instance-creation time to generate the value for us. Anonymous Functions Anonymous functions are another functional programming feature of Python.They are created using the lambda keyword and consist of a single expression, which represents the “return value” of the function. Such functions are not declared like a typical function and thus do not receive a name, hence the term anonymous function.They are usually single-line expressions that are meant to be created, used, and discarded in a general fashion.We should point out the distinction between “expressions” and “statements” so there is no confusion.

The following shows how those keyword arguments could also be passed as a dictionary: bobargs = {'title__contains': 'bob', 'subtitle__contains': 'bob', 'text__contains': 'bob', 'byline__contains': 'bob'} bob_stories = Story.objects.filter(**bobargs) Having done that, you can see how you would build up the dictionary dynamically: bobargs = dict((f + '__contains', 'bob') for f in ('title', 'subtitle', 'text', 'byline')) bob_stories = Story.objects.filter(**bobargs) Having done that, you can see how this technique could be helpful in streamlining queries with a lot of redundancy—or, even more commonly, helpful in assembling filter arguments whose names are provided dynamically (from options on a search form, for example). Decorators The last and perhaps most mind-bending concept when learning about Python functions and functional programming is decorators. In our context, a Python decorator is a mechanism enabling you to alter or “decorate” the behavior of a function to perform somewhat differently than designed, or to do something in addition to its native task; a decorator is a “function wrapper” if you will. Some of these extra tasks can include logging, timing, filtering, and so forth.

For example, you can create potentially large queries via looping. first_names = ["John", "Jane", "Jeremy", "Julia"] first_name_keywords = Q() # Empty "query" to build on for name in first_names: first_name_keywords = first_name_keywords | Q(first=name) specific_does = Person.objects.filter(last="Doe").filter(first_name_keywords) As you can see, we created a short for loop, primed it with the first item in our list, and then kept “appending” to the resulting Q object by using the | operator.This example actually isn’t the best—such a simple scenario would be served better by the __in query operator—but hopefully it illustrates the potential power of composing Q objects together programmatically. Note We could have saved a few lines in the previous example by using some functional programming tools Python provides, namely list comprehensions, the built-in method reduce, and the operator module. The operator module provides functional equivalents to operators, such as or_ for | and and_ for &. The three lines surrounding the for loop could have been rewritten as reduce(or_,[Q(first=name) for name in first_names]).

pages: 458 words: 135,206

CTOs at Work by Scott Donaldson, Stanley Siegel, Gary Donaldson

We're drifting away from the classic C#-, Java-, C++-style of object-oriented programming into more of a functional transformation style of programming, running data through transforms and templates that ultimately result in a web page. But that's definitely resulting in less code and simpler programs. S. Donaldson: Very interesting. Ballard: Functional programming is in a paradigm whether you use an explicit functional programming language or not, I think is important. Siegel: Let's shift gears for a minute and talk about technology investment. How does your company invest in technology? Ballard: We invest on multiple different levels. I alluded to this topic earlier when I was speaking about the ROI [return on investment] on a per-product basis.

Designing Data-Intensive Applications: The Big Ideas Behind Reliable, Scalable, and Maintainable Systems by Martin Kleppmann

MapReduce is neither a declarative query language nor a fully imperative query API, but somewhere in between: the logic of the query is expressed with snippets of code, which are called repeatedly by the processing framework. It is based on the map (also known as collect) and reduce (also known as fold or inject) functions that exist in many functional programming languages. To give an example, imagine you are a marine biologist, and you add an observation record to your database every time you see animals in the ocean. Now you want to generate a report saying how many sharks you have sighted per month. In PostgreSQL you might express that query like this: SELECT date_trunc('month', observation_timestamp) AS observation_month, sum(num_animals) AS total_animals FROM observations WHERE family = 'Sharks' GROUP BY observation_month; The date_trunc('month', timestamp) function determines the calendar month containing timestamp, and returns another timestamp representing the begin‐ ning of that month.

In principle, one type of processing can be emulated on top of the other, although the performance characteristics vary: for example, microbatching may perform poorly on hopping or sliding windows [6]. Maintaining derived state Batch processing has a quite strong functional flavor (even if the code is not written in a functional programming language): it encourages deterministic, pure functions whose output depends only on the input and which have no side effects other than the explicit outputs, treating inputs as immutable and outputs as append-only. Stream processing is similar, but it extends operators to allow managed, fault-tolerant state (see “Rebuilding state after a failure” on page 478).

Subscribing to changes is only just beginning to emerge as a feature (see “API support for change streams” on page 456). i. Explaining a joke rarely improves it, but I don’t want anyone to feel left out. Here, Church is a reference to the mathematician Alonzo Church, who created the lambda calculus, an early form of computation that is the basis for most functional programming languages. The lambda calculus has no mutable state (i.e., no vari‐ ables that can be overwritten), so one could say that mutable state is separate from Church’s work. 506 | Chapter 12: The Future of Data Systems Dataflow: Interplay between state changes and application code Thinking about applications in terms of dataflow implies renegotiating the relation‐ ship between application code and state management.

pages: 471 words: 94,519

Managing Projects With GNU Make by Robert Mecklenburg, Andrew Oram

To diagnose this problem, we examine make's internal database by running make with its —print-data-base option and we see something strange: \$make --print-database | grep ^ls ls_headers = ls.h glob.h ls_sources = ls.c glob.c ls_objects = ls.o glob.o ls.c: ls.o: ls.c ls: ls.o The .h prerequisites for ls.o are missing! There is something wrong with the rule using computed variables. When make parses the eval function call, it first expands the user-defined function, program-variables. The first line of the macro expands to: ls_sources = ls.c glob.c Notice that each line of the macro is expanded immediately as expected. The other variable assignments are handled similarly. Then we get to the rule: \$(\$1_objects): \$(\$1_headers) The computed variables first have their variable name expanded: \$(ls_objects): \$(ls_headers) Then the outer variable expansion is performed, yielding: : Wait!

pages: 544 words: 96,029

Practical C Programming, 3rd Edition by Steve Oualline

An apprentice builder does not start out building the Empire State Building, but rather starts on a one-room house. In this chapter, we will concentrate on constructing simple one-function programs. Basic Program Structure The basic elements of a program are the data declarations, functions, and comments. Let’s see how these can be organized into a simple C program. The basic structure of a one-function program is: /**************************************************** * ...Heading comments... * ****************************************************/ ...Data declarations... int main() { ...Executable statements... return (0); } Heading comments tell the programmer about the program, and data declarations describe the data that the program is going to use.

Exploring ES6 - Upgrade to the next version of JavaScript by Axel Rauschmayer

At the end, I’ll use the algorithm to explain the difference between the following two function declarations. function move({x=0, y=0} = {}) { ··· } function move({x, y} = { x: 0, y: 0 }) { ··· } 11.11.1 The algorithm A destructuring assignment looks like this: Destructuring 144 «pattern» = «value» We want to use pattern to extract data from value. I’ll now describe an algorithm for doing so, which is known in functional programming as pattern matching (short: matching). The algorithm specifies the operator ← (“match against”) for destructuring assignment that matches a pattern against a value and assigns to variables while doing so: «pattern» ← «value» The algorithm is specified via recursive rules that take apart both operands of the ← operator.

We read the contents of a text file via an asynchronous call to fs.readFile(): // Node.js fs.readFile('myfile.txt', { encoding: 'utf8' }, function (error, text) { // (A) if (error) { // ... } console.log(text); }); Asynchronous programming (background) 439 If readFile() is successful, the callback in line A receives a result via the parameter text. If it isn’t, the callback gets an error (often an instance of Error or a sub-constructor) via its first parameter. The same code in classic functional programming style would look like this: // Functional readFileFunctional('myfile.txt', { encoding: 'utf8' }, function (text) { // success console.log(text); }, function (error) { // failure // ... }); 24.3.3 Continuation-passing style The programming style of using callbacks (especially in the functional manner shown previously) is also called continuation-passing style (CPS), because the next step (the continuation) is explicitly passed as a parameter.

pages: 1,331 words: 183,137

Programming Rust: Fast, Safe Systems Development by Jim Blandy, Jason Orendorff

The Big Picture Rust’s enums may be new to systems programming, but they are not a new idea. Traveling under various academic-sounding names, like algebraic data types, they’ve been used in functional programming languages for more than 40 years. It’s unclear why so few other languages in the C tradition have ever had them. Perhaps it is simply that for a programming language designer, combining variants, references, mutability, and memory safety is extremely challenging. Functional programming languages dispense with mutability. C unions, by contrast, have variants, pointers, and mutability—but are so spectacularly unsafe that even in C, they’re a last resort.

The closure’s return value is taken as the new running total. The last value it returns is what fold itself returns—in this case, the total of the entire sequence. This may look strange if you’re used to for and while loops, but once you’ve gotten used to it, fold is a legible and concise alternative. This is pretty standard fare for functional programming languages, which put a premium on expressiveness. But Rust’s iterators were carefully designed to ensure that the compiler can translate them into excellent machine code as well. In a release build of the second definition shown before, Rust knows the definition of fold, and inlines it into triangle.

Terraform: Up and Running: Writing Infrastructure as Code by Yevgeniy Brikman

You can build an AMI from this template by running packer build web server.json, and once the build completes, you can deploy that AMI across all of your AWS servers, tell each one to fire up Apache on boot (you’ll see an example of this in the next section), and they will all run exactly the same way. Server templating is a key component of the shift to immutable infrastructure. This idea is inspired by functional programming, where variables are immutable, so once you’ve set a variable to a value, you can never change that variable again. If you need to update something, you create a new variable. Since variables never change, it’s a lot easier to reason about your code. The idea behind immutable infrastructure is similar: once you’ve deployed a server, you never make changes to it again.

pages: 211 words: 37,094

JQuery Pocket Reference by David Flanagan

These features are at the heart of jQuery’s power and utility: An expressive syntax (CSS selectors) for referring to elements in the document An efficient query method for finding the set of document elements that match a CSS selector A useful set of methods for manipulating selected elements Powerful functional programming techniques for operating on sets of elements as a group, rather than one at a time A succinct idiom (method chaining) for expressing sequences of operations This book begins with an introduction to jQuery that shows how to make simple queries and work with the results. The chapters that follow explain: How to set HTML attributes; CSS styles and classes; HTML form values; and element content, geometry, and data How to alter the structure of a document by inserting, replacing, wrapping, and deleting elements How to use jQuery’s cross-browser event model How to produce animated visual effects with jQuery jQuery’s Ajax utilities for making scripted HTTP requests jQuery’s utility functions The full syntax of jQuery’s selectors, and how to use jQuery’s advanced selection methods How to extend jQuery by using and writing plugins The jQuery UI library The end of this book is a quick reference to all of jQuery’s methods and functions.

pages: 194 words: 36,223

Smart and Gets Things Done: Joel Spolsky's Concise Guide to Finding the Best Technical Talent by Joel Spolsky

Sadly, despite the fact that I think that all good programmers should be able to handle recursion and pointers, and that this is an excellent way to tell if someone is a good programmer, the truth is that these days, programming languages have almost completely made that specific art unnecessary. Whereas ten years ago it was rare for a computer science student to get through college without learning recursion and functional programming in one class and C or Pascal with data structures in another class, today it’s possible in many otherwise reputable schools to coast by on Java alone.4 4. Joel Spolsky, “The Perils of JavaSchools,” published at www.joelonsoftware.com on December 29, 2005 (search for “JavaSchools”). The Guerrilla Guide to Interviewing 111 A lot of programmers whom you might interview these days are apt to consider recursion, pointers, and even data structures to be a silly implementation detail that has been abstracted away by today’s many happy programming languages.

pages: 924 words: 196,343

JavaScript & jQuery: The Missing Manual by David Sawyer McFarland

The result is something like the bottom image in Figure 11-6. In this example, the callback function was defined outside of the get() function; however, you can use an anonymous function (see Anonymous Functions) if you want to keep all of the Ajax code together: \$.get('file.php', data, function(data,status) { // callback function programming goes here }); For example, you could rewrite line 4 on Processing Data from the Server to use an anonymous function like this: \$.get('rate.php', querystring, function(data) { var newHTML; newHTML = '<h2>Your vote is counted</h2>'; newHTML += '<p>The average rating for this movie is '; newHTML += data + '.

Add one last line to the end of the keyup event function (line 10), so the completed script for the page looks like this: 1 <script> 2 \$(document).ready(function() { 3 console.log('READY'); 4 \$('#comments').keyup(function() { 5 console.log('Event: keyup'); 6 var text = \$(this).val(); 7 console.log('Contents of comments: %s',text); 8 var chars = text.length; 9 console.log('Number of characters: %d',chars); 10 \$('#count').text(chars + " characters"); 11 }); // end keyup 12 }); // end ready 13 </script> Save the file, and preview it in Firefox. Make sure Firebug is open, and the page and console should now look something like Figure 15-5. You’ll find a finished version of this tutorial—complete_console.html—in the chapter15 folder in the tutorials folder. Note Once you have a functioning program, you should remove all console.log() code from your script. The log() function will generate errors in some browsers. Figure 15-5. The Firebug console is a great way to print out diagnostic information as a program is running. You can also group together a series of log entries (for example, to group all the log messages printed during a loop) by adding console.group() before the first console.log() message in the group, and console.groupEnd() after the last message.

Fortunately, Firebug includes a powerful JavaScript debugger. It lets you step through a script line by line so you can see what’s happening at each step of the program. Note You’ll also find JavaScript debuggers with similar functionality in Chrome, Opera, Safari, and Internet Explorer 9. Debugging is the process of fixing an incorrectly functioning program—getting the bugs out. To really understand how a program is functioning (or malfunctioning), you need to see how the program works, step-by-step. To use the debugger, you mark certain lines of code as breakpoints. A breakpoint is a spot where the JavaScript interpreter stops running and waits.

pages: 273 words: 46,214

JavaScript: the good parts by Douglas Crockford

It is unfortunate that Java failed in that environment; if it hadn't, there could be a choice for people desiring a strongly typed classical language. But Java did fail and JavaScript is flourishing, so there is evidence that JavaScript did something right. The other answer is that, despite its deficiencies, JavaScript is really good. It is lightweight and expressive. And once you get the hang of it, functional programming is a lot of fun. But in order to use the language well, you must be well informed about its limitations. I will pound on those with some brutality. Don't let that discourage you. The good parts are good enough to compensate for the bad parts. 1.3. A Simple Testing Ground If you have a web browser and any text editor, you have everything you need to run JavaScript programs.

pages: 199 words: 47,154

Gnuplot Cookbook by Lee Phillips

He implemented the server-side scripting engine in the scheme-based SUnet web server, hosted the Learning-Classifier-System workshops in Tübingen. He has been the reviewer for numerous scientific articles, research proposals, and books, and has been a judge in the German Federal Competition in Computer Science on several occasions. His main interests are functional programming and machine-learning algorithms. David Millán Escrivá was 8 years old when he wrote his first program on 8086 PC with Basic language. He has more than 10 years of experience in IT. He has worked on computer vision, computer graphics, and pattern recognition. Currently he is working on different projects about computer vision and AR.

pages: 249 words: 45,639

Learn Python the Hard Way by Zed Shaw

What's the relationship between dir(something) and the "class" of something? If you do not have any idea what I'm talking about do not worry. Programmers like to feel smart so they invented Object Oriented Programming, named it OOP, and then used it way too much. If you think that's hard, you should try to use "functional programming". © Copyright 2010, Zed A. Shaw. Last updated on Jun 24, 2011. Exercise 40: Dictionaries, Oh Lovely Dictionaries Now I have to hurt you with another container you can use, because once you learn this container a massive world of ultra-cool will be yours. It is the most useful container ever: the dictionary.

pages: 309 words: 54,839

Attack of the 50 Foot Blockchain: Bitcoin, Blockchain, Ethereum & Smart Contracts by David Gerard

There were some smart contract experiments on Bitcoin, but Ethereum was pretty much the first practical platform for writing and running computer programs on a blockchain. Humans are bad at tasks requiring perfection. But when programming errors have drastic consequences, the usual approach is to make it harder to shoot yourself in the foot: functional programming languages, formal methods, mathematical verification of the code, don’t use a full computer language (avoid Turing completeness), and so on. Szabo wrote up some requirements and a simple example language in 2002.344 This is particularly important when you have multiple smart contracts interacting with each other – massively concurrent programming, with unknown possibly-hostile programs calling into functions of yours.

pages: 211 words: 58,677

Philosophy of Software Design by John Ousterhout

There has been considerable discussion about software development processes such as agile development and about development tools such as debuggers, version control systems, and test coverage tools. There has also been extensive analysis of programming techniques such as object-oriented programming and functional programming, and of design patterns and algorithms. All of these discussions have been valuable, but the core problem of software design is still largely untouched. David Parnas’ classic paper “On the Criteria to be used in Decomposing Systems into Modules” appeared in 1971, but the state of the art in software design has not progressed much beyond that paper in the ensuing 45 years.

pages: 504 words: 89,238

Natural language processing with Python by Steven Bird, Ewan Klein, Edward Loper

Processing Raw Text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 3.1 3.2 3.3 3.4 3.5 3.6 3.7 3.8 3.9 Accessing Text from the Web and from Disk Strings: Text Processing at the Lowest Level Text Processing with Unicode Regular Expressions for Detecting Word Patterns Useful Applications of Regular Expressions Normalizing Text Regular Expressions for Tokenizing Text Segmentation Formatting: From Lists to Strings 80 87 93 97 102 107 109 112 116 v 3.10 Summary 3.11 Further Reading 3.12 Exercises 121 122 123 4. Writing Structured Programs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 Back to the Basics Sequences Questions of Style Functions: The Foundation of Structured Programming Doing More with Functions Program Development Algorithm Design A Sample of Python Libraries Summary Further Reading Exercises 130 133 138 142 149 154 160 167 172 173 173 5. Categorizing and Tagging Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 179 5.1 5.2 5.3 5.4 5.5 5.6 5.7 5.8 5.9 5.10 Using a Tagger Tagged Corpora Mapping Words to Properties Using Python Dictionaries Automatic Tagging N-Gram Tagging Transformation-Based Tagging How to Determine the Category of a Word Summary Further Reading Exercises 179 181 189 198 202 208 210 213 214 215 6.

. >>> list(permutations(['police', 'fish', 'buffalo'])) [['police', 'fish', 'buffalo'], ['fish', 'police', 'buffalo'], ['fish', 'buffalo', 'police'], ['police', 'buffalo', 'fish'], ['buffalo', 'police', 'fish'], ['buffalo', 'fish', 'police']] The permutations function uses a technique called recursion, discussed later in Section 4.7. The ability to generate permutations of a set of words is useful for creating data to test a grammar (Chapter 8). Higher-Order Functions Python provides some higher-order functions that are standard features of functional programming languages such as Haskell. We illustrate them here, alongside the equivalent expression using list comprehensions. Let’s start by defining a function is_content_word() which checks whether a word is from the open class of content words. We use this function as the first parameter of filter(), which applies the function to each item in the sequence contained in its second parameter, and retains only the items for which the function returns True. 4.5 Doing More with Functions | 151 >>> def is_content_word(word): ... return word.lower() not in ['a', 'of', 'the', 'and', 'will', ',', '.'] >>> sent = ['Take', 'care', 'of', 'the', 'sense', ',', 'and', 'the', ...

Racing the Beam: The Atari Video Computer System by Nick Montfort, Ian Bogost

Warshaw told an interviewer that he had planned to use this method from the start rather than working it out as a solution to a problem that came up: “It was just a cheap way to get the effect I wanted. I didn’t have the time or space to do it any other way.”13 Still, by making the game’s code into an important visual component of Yars’ Revenge, Warshaw showed how a functioning program could shine aesthetically. When the player looks at the neutral zone on the screen, he is also literally looking at the code. Yars’ Revenge may not have had any direct inﬂuence on the spectacular movie Tron released the summer after the game, but the multicolored Master Control Program is cast in a different light by the neutral zone, actually drawn again and again by its own image, a liminal code-and-data Janus.

pages: 485 words: 74,211

Developing Web Applications with Haskell and Yesod by Michael Snoyman

As a real-life example, Yesod and Hamlet (the default templating language) use blaze-builder for textual content generation. This choice was made because blaze provides the fastest interface for generating UTF-8 data. Anyone who wants to use one of the other great libraries out there, such as text, should have no problem dropping it in. Introduction to Haskell Haskell is a powerful, fast, type-safe, functional programming language. This book takes as an assumption that you are already familiar with most of the basics of Haskell. There are two wonderful books for learning Haskell, both of which are available for reading online: Learn You a Haskell for Great Good! Real World Haskell Yesod relies on a few features in Haskell that most introductory tutorials do not cover.

Learning Node.js: A Hands-On Guide to Building Web Applications in JavaScript by Marc Wandschneider

param) throw new Error("Invalid Argument"); } One case where type comparisons can be tricky is if you use object constructors for values instead of just using primitives: > var x = 234; undefined > var x1 = new Number(234); undefined > typeof x1 'object' > typeof x 'number' > x1 == x true > x1 === x false > The object constructors are functionally equivalent to the primitive types; all the same operations, operators, and functions produce the same results, but the precise equality operator === and typeof operator produce different results. For this reason, it is recommended to just use the primitive types whenever possible. Functions Although it does not look like it at first glance (the name doesn’t help either), JavaScript is a functional programming language, wherein functions are fully typed objects that can be manipulated, extended, and passed around as data. Node.js takes advantage of this capability, and you will use it extensively in your network and web applications. Basics The simplest kind of function is exactly as you would expect: function hello(name) { console.log("hello " + name); } > hello("marc"); hello marc undefined > To declare parameters for a function in JavaScript, you simply list them in the parentheses.

pages: 681 words: 64,159

Numpy Beginner's Guide - Third Edition by Ivan Idris

Having learned about the basics, it's tme to move on to the study of commonly used functons in Chapter 3 , Getng Familiar with Commonly Used Functons , which includes basic statstcal and mathematcal functons. 3 Getting Familiar with Commonly Used Functions In this chapter, we will have a look at common NumPy functions. In particular, we will learn how to load data from files by using an example involving historical stock prices. Also, we will get to see the basic NumPy mathematical and statistical functions. We will learn how to read from and write to files. Also, we will get a taste of the functional programming and linear algebra possibilities in NumPy. In this chapter, we shall cover the following topics:  Functons working on arrays  Loading arrays from fles  Writng arrays to fles  Simple mathematcal and statstcal functons File I/O First, we will learn about fle I/O with NumPy. Data is usually stored in fles.

pages: 834 words: 180,700

The Architecture of Open Source Applications by Amy Brown, Greg Wilson

Riak consists of many complex applications, so this chapter should not be interpreted as a complete guide. It should be seen as an introduction to OTP where examples from the Riak source code are used. The figures and examples have been abbreviated and shortened for demonstration purposes. 15.1. An Abridged Introduction to Erlang Erlang is a concurrent functional programming language that compiles to byte code and runs in a virtual machine. Programs consist of functions that call each other, often resulting in side effects such as inter-process message passing, I/O and database operations. Erlang variables are single assignment, i.e., once they have been given values, they cannot be updated.

Riak was cleanly restarting each of these subsystems on demand, and the overall system simply continued to function. That experience shows exactly the sort of resilience enabled by Erlang/OTP's approach to building programs. 15.7.1. Acknowledgments This chapter is based on Francesco Cesarini and Simon Thompson's 2009 lecture notes from the central European Functional Programming School held in Budapest and Komárno. Major contributions were made by Justin Sheehy of Basho Technologies and Simon Thompson of the University of Kent. A special thank you goes to all of the reviewers, who at different stages in the writing of this chapter provided valuable feedback. The Architecture of Open Source Applications Amy Brown and Greg Wilson (eds.)

pages: 317 words: 76,169

The Perfect House: A Journey With Renaissance Master Andrea Palladio by Witold Rybczynski

While the deployment of these details formed the basis of Palladio’s style, the manner of deployment varied greatly. Sometimes he re-created entire parts of ancient buildings, such as the Villa Barbaro temple front, sometimes he merely sketched in a molding or two. The quantity and intensity of detail varied from abundant to minimal, depending on the circumstances of the commission—the site, the functional program, the budget, and the client. The last was a particularly important consideration, for Palladio believed that houses should not only be functional, well-built, and beautiful, but that they should also express what he called convenienza, or suitability. One must describe as suitable a house which will be appropriate to the status of the person who will have to live in it and of which the parts will correspond to the whole and to each other.

Microsoft Office Outlook 2010 QuickSteps by Malestrom

Enter the file name for the form, click Save, and close the form. 190 190 Microsoft Ofﬁce Outlook 2010 PC QuickSteps Getting to QuickSteps Know Your PCUsing Forms, Labels, and Mail Merge 1 USE THE DEVELOPER TAB Adding code and programming a form and working with add-ins are beyond the scope of this book. 2 NOTE The Developer tab and ribbon in the Form Design window allow you to perform the following functions: Program small scripts and macros to automate a form. Publish the form to a server so that you or anyone else with access can use it. 3 View Visual Basic script code you have added to the form. Display or rename a page. Create a new form region or rename a current one. Choose to edit the page as the sender or the reader will see it. 4 • • • • • • • • • Open and close the Field Chooser and the Control toolbox.

pages: 550 words: 84,515

Vue.js 2 Cookbook by Andrea Passaglia

Getting Started with Vue.js In this chapter the following recipes will be covered: Writing Hello World with Vue.js Writing lists Creating a dynamic and animated list Reacting to events such as clicks and keystrokes Choosing a development environment Formatting your text with filters Debugging your application with mustaches (for example, a JSON filter) X-raying your application with Vue developer tools Upgrading to Vue.js 2 Introduction Vue is a very powerful framework but one of its strengths is that it is very lightweight and easy to pick up. As a matter of fact, in the first recipe you will build a simple but functioning program in minutes, with no setup required. In this chapter, you will learn lists which will help you create web pages where an element is repeated (like a catalog). Furthermore, you will build an interactive page with event listeners. Some development environments are presented so you can choose the one that suits you better; you will use some debugging tricks that will give you a head start when developing your own code and better insight to kill bugs in your apps.

pages: 237 words: 74,109

Uncanny Valley: A Memoir by Anna Wiener

I tried to imagine a life in which I was simply her and the CEO’s third wheel. We could sit on the sidelines of the basketball court in Potrero Hill and watch him play pickup. She could teach me how to blow out my hair, and not just in the front. I pictured us going on vacations together, the three of us drinking seltzer and discussing functional programming. Perhaps I, too, could become an executive if I hung out with present and future executives. I would have access to the inside track. We could go on weekend getaways to Sonoma, rent entire houses on the home-sharing platform and stand around marble kitchen islands sipping biodynamic wines and sharing our business ideas.

pages: 1,409 words: 205,237

Architecting Modern Data Platforms: A Guide to Enterprise Hadoop at Scale by Jan Kunigk, Ian Buss, Paul Wilkinson, Lars George

Although superseded by newer engines, such as Apache Spark and Apache Flink, it is still worth understanding, given that many higher-level frameworks compile their inputs into MapReduce jobs for execution. These include: Apache Hive Apache Sqoop Apache Oozie Apache Pig Note The terms map and reduce are borrowed from functional programming, where a map applies a transform function to every element in a collection, and a reduce applies an aggregation function to each element of a list, combining them into fewer summary values. Essentially, MapReduce divides a computation into three sequential stages: map, shuffle, and reduce.

Coding Whereas the typical analyst or statistician understands methods and models mathematically, a good data scientist also has a solid background in parallel algorithms to build large-scale distributed applications around such models. As we already mentioned, the data scientist is well versed in coding in third-generation and functional programming languages, such as Scala, Java, and Python, in addition to the domain-specific languages of the classic analytics world. In this function, the data scientist collaborates with development departments to build fully fledged distributed applications that can be productively deployed to Hadoop.

The Art of Scalability: Scalable Web Architecture, Processes, and Organizations for the Modern Enterprise by Martin L. Abbott, Michael T. Fisher

Art of scalability, 2–3 Artificial Intelligence, 427–428 Assessing your situation, 502 Asynchronous chat room communication, crisis management, 157–158 Asynchronous coordination, 397–398 Asynchronous design AMI (asynchronous method invocation), 395–396 architectural principles, 202, 205–206 asynchronous coordination, 397–398 asynchronous scaling, vs. synchronous, 396–398 asynchronous systems, example, 398–401 avoiding session storage, 403–404, 405 centralizing session storage, 404, 405 Christmas tree lights analogy, 400–401 cyclomatic complexity, 400 decentralizing session storage, 404, 405 declarative programming, 402 defining state, 401 dining philosophers problem, 394 functional programming, 402 imperative programming, 402 logical programming, 402 Mealy machines, 401–402 Moore machines, 401–402 multiplicative effect of failures, 400–401 mutex synchronization, 394 mutual exclusion synchronization, 394 537 538 I NDEX Asynchronous design (continued) object-oriented programming, 402 procedural programming, 402 session environments, saving, 403–404 state, saving, 403–404 structured programming, 402 synchronization process, description, 393–394 synchronous calls, example, 395 synchronous calls vs. asynchronous, 395–401 synchronous systems, scaling issues, 398–401 Asynchronous method invocation (AMI), 395–396 Asynchronous scaling, vs. synchronous, 396–398 Asynchronous systems, example, 398–401 Atomicity, Consistency, Isolation, Durability (ACID) database properties, 383 Autonomic Computing Manifesto (IBM), 427–428 Availability fault isolation, 312–315 TAA effects, 306 TAD effects, 306 Availability, calculating customer complaints, 515–516 hardware uptime, 514–515 overview, 513–514 portion of site down, 516–517 third-party monitoring, 517–518 traffic graphs, 518–519 Axes, AKF Scale Cube.

See Cost, of scalability failure. detection, 249 likelihood, 249 multiplicative effect of, 400–401 risk management, 249 severity, 249 stress testing, 265 Failure Mode and Effects Analysis (FMEA), 249–251 Fault isolation design checklist, 321 markdown functionality, 313–314 poddings, definition, 310 pods, definition, 310, 311 pools, definition, 311 sharding, definition, 311 shards, definition, 311 slivers, definition, 311 terminology, 310–311 testing, 321–322 x-axis splits, 343 y-axis splits, 345 z-axis splits, 346 Fault isolation, approaches to along natural barriers, 320–321 by the biggest sources of incidents, 320 design checklist, 321 isolating the money-maker, 320 Fault isolation, benefits of availability, 312–315 cost, 316–317 effects on revenue, 317 incident detection, 315 incident resolution, 315 scalability, 315 time to market, 315–316 Fault isolation, design principles design checklist, 321 nothing crosses a swim lane boundary, 319 nothing is shared, 318 transactions occur along swim lanes, 319 Fault isolation, swim lanes along natural barriers, 320–321 545 546 I NDEX Fault isolation, swim lanes (continued) by the biggest sources of incidents, 320 by customer boundaries, 312–313 definition, 310, 311 isolating the money-maker, 320 by service boundaries, 313–314 Feature selection, ARB (Architecture Review Board), 228 Feature significance, JAD (Joint Architecture Design), 217 Feedback from teams, business processes, 131 Feeding teams, 98 Final design, documenting in JAD (Joint Architecture Design), 218–219 Fisher, Mike, 506, 507–508 Flexibility, cloud computing benefit, 442 FMEA (Failure Mode and Effects Analysis), 249–251 Follow up communication, crisis management, 162 Formal training, leadership, 68 Forward proxy caches. See Proxy caches. Foster, Ian, 428 Functional organization. See Team structure, functional organization. Functional programming, 402 middleware providers, 429 public vs. private networks, 429 Grid computing, uses for back office grid, 464 build grid, 462–463 data warehouse grid, 463–464 MapReduce, 464 production grid, 461–462 SETI@home project, 429 Grids, cons complexity, 459–460 monolithic applications, 459 not shared simultaneously, 459 summary of, 460 Grids, pros cost, 457–458 high computational rates, 456–457 shared infrastructure, 457 summary of, 458 utilization of unused capacity, 457 Grids, vs. clouds, 434–436 Guidelines.

RDF Database Systems: Triples Storage and SPARQL Query Processing by Olivier Cure, Guillaume Blin

To apprehend the full potential of this approach, this also has Database Management Systems to come with methods to process this data efficiently—that is, to perform the processing on the servers and to limit the transfer of data between machines to its minimum. ­MapReduce, a programming model that has been proposed by engineers at Google in 2004 (Dean and Ghemawat, 2004), is such a framework. It’s based on two operations that have existed for decades in functional programming: the map and reduce functions. In a MapReduce framework, the user programs the map and reduce functions in a given programming language, such as Java or C++. But abstractions to program these two functions are available using an SQL-like query language, such as PIG LATIN. When writing these programs, one does not need to take care about the data distribution and parallelism aspects.

Data and the City by Rob Kitchin,Tracey P. Lauriault,Gavin McArdle

Notes 1 McLuhan’s work, famously stating that ‘the medium is the message’, can be read as an early intervention into this predominant framing of media as a passive carrier (McLuhan 1994 [1964]). 2 Latour makes an analogous argument regarding sociologists’ various efforts to come to an arrangement between interaction- and structure-based perspectives: ‘The combination of two artifacts could only produce a third, yet more annoying, one’ (Latour 1996: 234). Situating data infrastructures 167 3 Notably, some functional programming languages (e.g. Lisp) follow the principle of homoiconicity, that is, they allow any piece of code to be handled like data, and vice versa. 4 For a more encompassing discussion of the assemblage in the social sciences and geography more specifically, see Marcus and Saka (2006) and Anderson and McFarlane (2011), respectively.

pages: 377 words: 110,427

The Boy Who Could Change the World: The Writings of Aaron Swartz by Aaron Swartz, Lawrence Lessig

For djb’s programs are not great machines to be admired from a distance, vast powerhouses of elegant accomplishment. They are also tools meant to be used by man, perfectly fitted to one’s hand. Like a great piece of industrial design, they bring joy to the user every time they are used. What other field combines all these arts? Language, math, art, design, function. Programming is clearly in a class of its own. And, when it comes to programmers, who even competes with djb? Who else has worked to realize these amazing possibilities? Who else even knows they are there? Oddly, there are many people who profess to hate djb. Some of this is just the general distaste of genius: djb clearly has a forceful, uncompromising vision, which many misinterpret as arrogance and rudeness.

pages: 446 words: 102,421

Network Security Through Data Analysis: Building Situational Awareness by Michael S Collins

Python Geospatial Development - Second Edition by Erik Westra

Python has been used to write web-based systems, desktop applications, games, scientific programming, and even utilities and other higher-level parts of various operating systems. Python supports a wide range of programming idioms, from straightforward procedural programming to object-oriented programming and functional programming. While Python is generally considered to be an "interpreted" language, and is occasionally criticized for being slow compared to "compiled" languages such as C, the use of byte-compilation and the fact that much of the heavy lifting is done by library code means that Python's performance is often surprisingly good.

pages: 461 words: 106,027

Zero to Sold: How to Start, Run, and Sell a Bootstrapped Business by Arvid Kahl

If there are a lot of tutorials and the technology seems well-documented at first glance, it will likely be around for quite a while. Look for a vibrant community. I've noticed that in the Elixir/Phoenix community developers are very engaged, and they love spending time educating other developers about the intricacies of this functional programming language and the ecosystem. When you're new to a programming language or just not as advanced as you need to be to solve your problem, you will have to learn the lay of the land before you can dive into building your product: what are the libraries you will need to use for certain parts?

pages: 470 words: 109,589

Apache Solr 3 Enterprise Search Server by Unknown

He's worked in dot-coms on almost everything related to web application development, from architecture to user experience. He's very active in the open source community, having contributed to several projects and started many projects of his own. In 2007 he wrote SolrNet, a popular open source Solr interface for the .NET platform. Currently he's also researching the application of functional programming to web development as part of his Master's thesis. He blogs at http://bugsquash.blogspot.com. www.PacktPub.com This book is published by Packt Publishing. You might want to visit Packt's website at www.PacktPub.com and take advantage of the following features and offers: Discounts Have you bought the print copy or Kindle version of this book?

pages: 429 words: 114,726

The Computer Boys Take Over: Computers, Programmers, and the Politics of Technical Expertise by Nathan L. Ensmenger

Although these languages benefited from ALGOL, they only detracted from its efforts to emerge as a standard. With a few noticeable exceptions—the ACM continued to use it as the language of choice in its publications, for example—ALGOL was generally regarded in the United States as an intellectual curiosity rather than a functional programming language. The real question of historical interest, of course, is not so much why specific individual programming languages were created but rather why so many. In the late 1940s and early 1950s there was no real programming community per se, only particular projects being developed at various institutions.

pages: 1,064 words: 114,771

Tcl/Tk in a Nutshell by Paul Raines, Jeff Tranter

For subtle details, you will sometimes want to consult the official Tcl reference documentation, but for most tasks you should find the answer you need in this volume. We hope that this guide will become an invaluable desktop reference for the Tcl user. Conventions This desktop quick reference uses the following typographic conventions: Italic Used for commands, methods, functions, programs, and options. All terms shown in italic are typed literally. Italic is also used for filenames and URLs, and to highlight terms under discussion. Constant width Used for code in program listings and for data structures and values to be entered exactly as shown. Also used for special variables, global variables, options showing resource and class names, and subwidget names.

pages: 394 words: 118,929

Dreaming in Code: Two Dozen Programmers, Three Years, 4,732 Bugs, and One Quest for Transcendent Software by Scott Rosenberg

Anderson mocked up the first crude version of a user interface in wxWidgets and wxPython. Hertzfeld whipped up a quick rendition of an address book or contacts manager. But without knowing how the program would store its data, nobody wanted to write too much; it felt like throwing walls up before you had even picked a site for a foundation. A functioning program still seemed like a mirage: No matter how many meetings the developers held or how many decisions they thought they had made, the goal moved no closer. Part of the problem was that although Kapor was the ultimate arbiter of all things Chandler, he felt out of his depth in the repository debate and didn’t want to dictate one approach over another.

pages: 385 words: 123,168

Bullshit Jobs: A Theory by David Graeber

Most of the time, the needs I am trying to fill are either my own need for a box ticker or a duct taper, or the needs of other managers, sometimes to hire people for non-BS work or to hire their ration of goons and flunkies. The reason I need duct tapers is usually because I have to compensate for poorly functioning program-management systems (both automated and human workflows) and, in some cases, a poorly functioning box ticker and even a non-BS-job subordinate who has job tenure and twenty-five years of outstanding performance ratings from a succession of previous bosses. This last is important. Even in corporate environments, it is very difficult to remove an underling for incompetence if that underling has seniority and a long history of good performance reviews.

pages: 960 words: 125,049

Mastering Ethereum: Building Smart Contracts and DApps by Andreas M. Antonopoulos, Gavin Wood Ph. D.

The Trade Lifecycle: Behind the Scenes of the Trading Process (The Wiley Finance Series) by Robert P. Baker

Quants also make heavy use of published papers and articles which could come from pure or applied mathematics, economics, finance and other disciplines, such as engineering and quantum physics. There is still widespread use of old-fashioned paper and pencil together with the more sophisticated spreadsheets and algorithm generator tools, such as Mathcad. 270 THE TRADE LIFECYCLE Nowadays most quants also do programming. Often they like the older, more functional programming languages such as C and Fortran, although the object-oriented C++ has become more commonly accepted. Quants want a language that allows them to write mathematics in programmatic code and that will run fast and be easy to debug if there are problems. They also want to be able to reuse common functions.

pages: 752 words: 131,533

Python for Data Analysis by Wes McKinney

= b True if a is not equal to b a <= b, a < b True if a is less than (less than or equal) to b a > b, a >= b True if a is greater than (greater than or equal) to b a is b True if a and b reference same Python object a is not b True if a and b reference different Python objects Strictness versus laziness When using any programming language, it’s important to understand when expressions are evaluated. Consider the simple expression: a = b = c = 5 d = a + b * c In Python, once these statements are evaluated, the calculation is immediately (or strictly) carried out, setting the value of d to 30. In another programming paradigm, such as in a pure functional programming language like Haskell, the value of d might not be evaluated until it is actually used elsewhere. The idea of deferring computations in this way is commonly known as lazy evaluation. Python, on the other hand, is a very strict (or eager) language. Nearly all of the time, computations and expressions are evaluated immediately.

pages: 303 words: 67,891

Advances in Artificial General Intelligence: Concepts, Architectures and Algorithms: Proceedings of the Agi Workshop 2006 by Ben Goertzel, Pei Wang

This section deals mainly with the former two; and the next section deals mainly with the latter two. 1.1. NCE Knowledge Representation The NCE utilizes a knowledge representation in which declarative knowledge is represented using weighted, labeled hypergraphs; procedural knowledge is represented using programs in a customized functional programming language called Combo; and mechanisms are in place for freely converting between declarative and procedural knowledge. Nodes and links in the declarative-knowledge hypergraph are grouped together into the category of “Atoms.” Atoms are quantified with truth values (see Fig. 1) that, in their simplest form, have two components, one representing probability (“strength”) and the other representing “weight of evidence”; and also with “attention values” (see Fig. 2) that have two components, short-term and long-term importance, representing the estimated value of the Atom on immediate and long-term time-scales.

pages: 525 words: 149,886

Higher-Order Perl: A Guide to Program Transformation by Mark Jason Dominus

Mark Foster also arrived from nowhere in the nick of time to suggest the title for this book just when I thought all was lost. This book was directly inspired by two earlier books: ML for the Working Programmer, by Lawrence Paulson, and Structure and Interpretation of Computer Programs, by Harold Abelson and Gerald Jay Sussman. Other important influences were Introduction to Functional Programming, by Richard Bird and Philip Wadler, and Paradigms of Artificial Intelligence Programming, by Peter Norvig. The official technical reviewers had a less rewarding job than they might have on other projects. This book took a long time to write, and although I wanted to have long conversations with the reviewers about every little thing, I was afraid that if I did that, I would never ever finish.

pages: 560 words: 135,629

Eloquent JavaScript: A Modern Introduction to Programming by Marijn Haverbeke

Then you’ll learn about error handling and bug fixing, modularity, and asynchronous programming before moving on to programming web browsers. As you build projects such as a browser game, a simple programming language, and a paint program, you’ll learn how to: Understand the essential elements of programming, including syntax, control, and data Organize and clarify your code with object-oriented and functional programming techniques Script the browser and make basic web applications Use the DOM effectively to interact with browsers Harness Node.js to build servers and utilities Isn’t it time you became fluent in the language of the web? About the Author Marijn Haverbeke is a programming language enthusiast and polyglot.

Principles of Protocol Design by Robin Sharp

This text was originally written for third or fourth year students in Computer Science or Electrical Engineering, and is intended to be suitable for most final-year undergraduate or postgraduate courses on advanced data communications or computer networks. The reader is expected to have a software background, in particular including a basic knowledge of functional programming and parallel programming, combined with some knowledge of computer systems architecture and data transmission. Knowledge of formal methods, for example based on languages such as VDM or Z, is not essential, but to get the most out of the book you should know about the sort of discrete mathematics which is used in computer science, and be aware of the basic concepts of mathematical proof.

pages: 696 words: 143,736

The Age of Spiritual Machines: When Computers Exceed Human Intelligence by Ray Kurzweil

However, in a discussion I had with Murray Campbell, head of the Deep Blue team, just weeks prior to its 1997 historic victory, Campbell agreed that Deep Blue’s evaluation method was more simple minded than complicated minded. MATH LESS “PSEUDO CODE” FOR THE RECURSIVE ALGORITHM Here is the basic schema for the recursive algorithm. Many variations are possible, and the designer of the system needs to provide certain critical parameters and methods, detailed below. The Recursive Algorithm Define a function (program), “PICK BEST NEXT STEP.” The function returns a value of “SUCCESS” (we’ve solved the problem) or “FAILURE” (we didn’t solve it). If it returns with a value of SUCCESS, then the function also returns the sequence of selected steps that solved the problem. PICK BEST NEXT STEP does the foliowing: PICK BEST NEXT STEP: • Determine if the program can escape from continued recursion at this point.

pages: 603 words: 141,814

Python for Unix and Linux System Administration by Noah Gift, Jeremy M. Jones

Hybrid Kudzu Design Pattern: Wrapping a Tool in Python, and Then Changing the Behavior In our last example, we made snmpdf quite a bit easier to use, but we didn’t change the basic behavior of the tool. The output of both tools was identical. Another approach we can use is to not only engulf a Unix tool, but to then change the basic behavior of the tool with Python as well. In the next example, we use Python’s generators in a functional programming style to filter the results of our snmpdf command to search for critical information, and then append a "CRITICAL" flag to it. Example 13-11 shows what it looks like. Example 13-11. Altering the SNMPDF command with generators #!/usr/bin/env python import optparse from subprocess import Popen, PIPE import re def main(): p = optparse.OptionParser(description="Python wrapped snmpdf command", prog="pysnmpdf", version="0.1a", usage="%prog machine") p.add_option("-c", "--community", help="snmp community string") p.add_option("-V", "--Version", help="snmp version to use") p.set_defaults(community="public",Version="2c") options, arguments = p.parse_args() SNMPDF = "snmpdf" if len(arguments) == 1: machine = arguments[0] #We create a nested generator function def parse(): """Returns generator object with line from snmpdf""" ps = Popen([SNMPDF, "-c", options.community, "-v",options.Version, machine], stdout=PIPE, stderr=PIPE) return ps.stdout #Generator Pipeline To Search For Critical Items pattern = "9[0-9]%" outline = (line.split() for line in parse()) #remove carriage returns flag = (" ".join(row) for row in outline if re.search(pattern, row[-1])) #patt search, join strings in list if match for line in flag: print "%s CRITICAL" % line #Sample Return Value #Real Memory 2067636 1974120 93516 95% CRITICAL else: p.print_help() if __name__ == '__main__': main() If we run our new “altered” version of snmpdf we get this output on test machine: [ngift@Macintosh-8][H:10486][J:0]# python snmpdf_alter.py localhost Real Memory 2067636 1977208 90428 95% CRITICAL We now have a completely different script that will only generate output if a value in snmpdf is 90 percent or higher, which we have signified as critical.

pages: 757 words: 193,541

The Practice of Cloud System Administration: DevOps and SRE Practices for Web Services, Volume 2 by Thomas A. Limoncelli, Strata R. Chalup, Christina J. Hogan

It is similar to Perl and Python in syntax, but adds features that make it easy to create mini-languages, purpose-built for a specific task. More programs can then be written in that mini-language. Scripting languages are more flexible and versatile than shell scripts. They are more expressive, permit better code organization, scale better, and encourage more modern coding practices such as object-oriented coding and functional programming. Better testing tools are available, and there are more prewritten libraries. Scripting languages have the ability to access networks, storage, and databases more easily than shell scripts. Better error checking is also available. Perl, Python, and Ruby all have large libraries of modules that perform common system administration tasks such as file manipulation, date and time handling, transactions using protocols such as HTTP, and database access.

HBase: The Definitive Guide by Lars George

There are a variety of ways to include HBase as a source and target for MapReduce jobs. Native Java The Java-based MapReduce API for HBase is discussed in Chapter 7. Clojure The HBase-Runner project (https://github.com/mudphone/hbase-runner/) offers support for HBase from the functional programming language Clojure. You can write MapReduce jobs in Clojure while accessing HBase tables. Hive The Apache Hive project[76] offers a data warehouse infrastructure atop Hadoop. It was initially developed at Facebook, but is now part of the open source Hadoop ecosystem. Hive offers an SQL-like query language, called HiveQL, which allows you to query the semistructured data stored in Hadoop.

Algorithms in C++ Part 5: Graph Algorithms by Robert Sedgewick

to the same tree in this forest. Figure 19.28 illustrates this fact for our example, and we will prove it in a moment. Therefore, we can assign component numbers as we did for undirected graphs, incrementing the component number each time that the recursive function returns to the top-level search function. Program 19.10 is a full implementation of the method. Property 19.14 Kosaraju’s method finds the strong components of a graph in linear time and space. Proof: The method consists of minor modifications to two DFS procedures, so the running time is certainly proportional to V2 for dense graphs and V + E for sparse graphs (using an adjacency-lists representation), as usual.

pages: 619 words: 210,746

Reversing: Secrets of Reverse Engineering by Eldad Eilam

The general idea is that a Trojan horse is an innocent artifact openly delivered through the front door when it in fact contains a malicious element hidden somewhere inside of it. In the software world, this translates to seemingly innocent files that actually contain some kind of malicious code underneath. Most Trojans are actually functional programs, so that the user never becomes aware of the problem; the functional element in the program works just fine, while the malicious element works behind the user’s back to promote the attacker’s interests. It’s really quite easy to go about hiding unwanted functionality inside a useful program.

PostGIS in Action by Regina O. Obe, Leo S. Hsu

We also think they’re pretty cool languages in their own right. They’re favorites among geostatisticians and GIS programmers. PL/Python and PL/R only come in the untrusted form; PL/V8 only comes trusted. Python is a dynamically typed, all-purpose procedural language. It has elegant approaches for creating and navigating objects, and it supports functional programming, object-oriented programming, the building of classes, metaprogramming, reflection, map reduce, and all those chic programming paradigms you’ve probably heard of. R, on the other hand, is more of a domain language. R is specifically designed for statistics, graphing, and data mining, so it draws a large following from research institutions.

pages: 1,085 words: 219,144

Solr in Action by Trey Grainger, Timothy Potter

In fact, the need to build a web-scale inverted index led to the invention of MapReduce. MapReduce is a programming model that distributes large-scale data-processing operations across a cluster of commodity servers by formulating an algorithm into two phases: map and reduce. With its roots in functional programming, MapReduce was adapted by Google for building its massive inverted index to power web search. Using MapReduce, the map phase produces a unique term and document ID where the term occurs. In the reduce phase, terms are sorted so that all term/docID pairs are sent to the same reducer process for each unique term.

pages: 933 words: 205,691

Hadoop: The Definitive Guide by Tom White

A natural question to ask is: can you do anything useful or nontrivial with it? The answer is yes. MapReduce was invented by engineers at Google as a system for building production search indexes because they found themselves solving the same problem over and over again (and MapReduce was inspired by older ideas from the functional programming, distributed computing, and database communities), but it has since been used for many other applications in many other industries. It is pleasantly surprising to see the range of algorithms that can be expressed in MapReduce, from image analysis, to graph-based problems, to machine learning algorithms.[8] It can’t solve every problem, of course, but it is a general data-processing tool.

pages: 761 words: 231,902

The Singularity Is Near: When Humans Transcend Biology by Ray Kurzweil

Sam Williams, "When Machines Breed," August 12,2004, http://www.salon.com/tech/feature/2004/08/12/evolvable_hardware/index_np.html. 177. Here is the basic scheme (algorithm description) of recursive search. Many variations are possible, and the designer of the system needs to provide certain critical parameters and methods, detailed below. THE RECURSIVE ALGORITHM Define a function (program) "Pick Best Next Step." The function returns a value of "SUCCESS" (we've solved the problem) or "FAILURE" (we didn't solve it). If it returns with a value of SUCCESS, then the function also returns the sequence of steps that solved the problem. PICK BESTNEXT STEP does the following: · Determine if the program can escape from continued recursion at this point.

PostGIS in Action, 2nd Edition by Regina O. Obe, Leo S. Hsu

We also think they’re pretty cool languages in their own right. They’re favorites among geostatisticians and GIS programmers. PL/Python and PL/R only come in the untrusted form; PL/V8 only comes trusted. Python is a dynamically typed, all-purpose procedural language. It has elegant approaches for creating and navigating objects, and it supports functional programming, object-oriented programming, the building of classes, metaprogramming, reflection, map reduce, and all those chic programming paradigms you’ve probably heard of. Licensed to tracy moore <nordick.an@gmail.com> www.it-ebooks.info 418 CHAPTER 16 Extending PostGIS with pgRouting and procedural languages R, on the other hand, is more of a domain language.

pages: 903 words: 235,753

The Stack: On Software and Sovereignty by Benjamin H. Bratton

Cars with Apps, medical devices with Apps, or any machine with Apps also suggest design assignments for modular forms of bottom-up artificial intelligence. Any machine, whether general or highly specific, could be imbued with the narrowly focused intelligence of the App linked to a wider Cloud and could download any particular sensing, sensory, storing, calculative, or transmission function programmed for it. Each can do that without addressing humans or requesting our interference in the communication flow between machine User and Cloud. The most important, viable, and effective Apps and App market platforms may serve the nonhuman Users that interface across scales and systems—manufacturing, logistics, healthcare, transportation, agriculture, retail service—by linking and delinking modular functions of component machines working in interoperable concert.44 In this economy, the universal flexibility of the “hand” dissipates into a more open field of tactical computation animating all programmable platform components more equally.

pages: 1,156 words: 229,431

The IDA Pro Book by Chris Eagle

If for some reason you fail to specify an index when you want to delete a single element, you may end up deleting an entire array. Similar functions exist to delete supval, charval, and hashval data. Useful SDK Datatypes IDA’s API defines a number of C++ classes designed to model components typically found in executable files. The SDK contains classes to describe functions, program sections, data structures, individual assembly language instructions, and individual operands within each instruction. Additional classes are defined to implement the tools that IDA uses to manage the disassembly process. Classes falling into this latter category define general database characteristics, loader module characteristics, processor module characteristics, and plug-in module characteristics, and they define the assembly syntax to be used for each disassembled instruction.

The Dream Machine: J.C.R. Licklider and the Revolution That Made Computing Personal by M. Mitchell Waldrop

In other words, Lisp could be written in Lisp, with only a very small kernel of machine code to keep it moored to the physical operation of the com- puter. That Lisp kernel, known as apply, thus provided a particularly elegant example of a uni- versal Turing machine: it was the universal function that took the definition of any other function as input and then executed that function. By no coincidence, McCarthy imple- mented this kind of functional programming in Lisp using the notation of the "lambda calcu- lus," which Alonzo Church had created twenty years earlier to solve the decidabihty problem, and which had allowed him to beat Alan Turing to the punch. THE TALE OF THE FIG TREE AND THE WASP 173 run it all, and he even had everything in place to run the world's first demon- stration of that scheme-everything, that is, except the blasted interrupt handler, which IBM still hadn't delivered.

pages: 923 words: 516,602

The C++ Programming Language by Bjarne Stroustrup

[UNIX,1985] UNIX Time-Sharing System: Programmer’s Manual. Research Version, Tenth Edition. AT&T Bell Laboratories, Murray Hill, New Jersey. February 1985. [Wilson,1996] Gregory V. Wilson and Paul Lu (editors): Parallel Programming Using C++. The MIT Press. Cambridge. Mass. 1996. ISBN 0-262-73118-5. [Wikström,1987] Åke Wikström: Functional Programming Using ML. Prentice-Hall. Englewood Cliffs, New Jersey. 1987. [Woodward,1974] P. M. Woodward and S. G. Bond: Algol 68-R Users Guide. Her Majesty’s Stationery Office. London. England. 1974. References to books relating to design and larger software development issues can be found at the end of Chapter 23.