27,59 €
Discover how to use the next-generation language Red for full-stack development, from systems coding over user-interfaces to blockchain programming
Key FeaturesExplore the latest features of Red to build scalable, fast, and secure applicationsLearn graphical programming and build highly sophisticated reactive applicationsGet familiar with the specific concepts and techniques of Red development, like working with series, viewing code as data, and using dialects.Book Description
A key problem of software development today is software bloat, where huge toolchains and development environments are needed in software coding and deployment. Red significantly reduces this bloat by offering a minimalist but complete toolchain. This is the first introductory book about it, and it will get you up and running with Red as quickly as possible.
This book shows you how to write effective functions, reduce code redundancies, and improve code reuse. It will be helpful for new programmers who are starting out with Red to explore its wide and ever-growing package ecosystem and also for experienced developers who want to add Red to their skill set.
The book presents the fundamentals of programming in Red and in-depth informative examples using a step-by-step approach. You will be taken through concepts and examples such as doing simple metaprogramming, functions, collections, GUI applications, and more. By the end of the book, you will be fully equipped to start your own projects in Red.
What you will learn Set up your Red environment to achieve the highest productivity Get grounded in Red, gaining experience and insight through many examples and exercises Build simple, compact, and portable applications Analyze streams of data through Parse Compose GUI applications with View and Draw Get prepared for smart contract blockchain programming in RedWho this book is for
This book is for software developers and architects who want to learn Red because of its conciseness, flexibility, and expressiveness, and more specifically for its possibilities in GUI apps and blockchain / smart contracts programming. Some knowledge of the basic concepts and experience of any programming language is assumed.
Ivo Balbaert is a former lecturer for (Web) programming and databases at CVO Antwerpen, a community college in Belgium. He received a PhD in applied physics from the University of Antwerp in 1986. He worked for 20 years in the software industry as a developer and consultant in several companies, and for 10 years as a project manager at the University Hospital of Antwerp. Since 2000, he has been partly teaching, developing software, and writing technical books, among others: • Rust Essentials • Getting Started with Julia • The Way to Go
Sie lesen das E-Book in den Legimi-Apps auf:
Seitenzahl: 291
Veröffentlichungsjahr: 2018
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. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing or its dealers and distributors, will be held liable for any damages caused or alleged to have been caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
Commissioning Editor: Richa TripathiAcquisition Editor: Denim PintoContent Development Editor: Akshada IyerTechnical Editor: Abhishek SharmaCopy Editor: Safis EditingProject Coordinator: Prajakta NaikProofreader: Safis EditingIndexer: Tejal Daruwale SoniGraphics: Jisha ChirayilProduction Coordinator: Shraddha Falebhai
First published: May 2018
Production reference: 1170518
Published by Packt Publishing Ltd. Livery Place 35 Livery Street Birmingham B3 2PB, UK.
ISBN 978-1-78913-070-6
www.packtpub.com
Mapt is an online digital library that gives you full access to over 5,000 books and videos, as well as industry leading tools to help you plan your personal development and advance your career. For more information, please visit our website.
Spend less time learning and more time coding with practical eBooks and Videos from over 4,000 industry professionals
Improve your learning with Skill Plans built especially for you
Get a free eBook or video every month
Mapt is fully searchable
Copy and paste, print, and bookmark content
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters, and receive exclusive discounts and offers on Packt books and eBooks.
When a new language is created, programmers and technology pundits are quick to ask "Why?," whether it's a programming, markup, or modeling language. Designers are often criticized, rather than praised, as if looking for new and better approaches is a bad thing. The critics couldn't be more wrong. That doesn't mean every new tool or idea will succeed, in theory or in practice. However, we must keep trying, if we hope to move forward or even keep pace. The world isn't standing still, and neither can we. As a conservative technologist (nee Luddite), I have to be reminded of this from time to time.
When an author, in this day and age, writes a book about technology, others are quick to ask "Why? Isn't everything you need to know available on the internet?." Sure, if you know where to look, are able to separate the wheat from the chaff (Luddites love time-tested idioms), and your noble goal is to work from original sources. If, however, you're a programmer in 2018, you may not have the luxury and time for pure research about every new technology that comes along, at an ever-increasing pace.
At this point, you're looking for a TL;DR (Too Long; Didn't Read), right? You're three paragraphs in, and already feeling pressured to move on. Your time is valuable and isn't to be wasted. I couldn't agree more. That's why you should read this book. It is a TL;DR for the Red language, and the Red language is your TL;DR for software development.
If you've never heard of Red, you don't know what makes it special, how to use it, or what it's capable of. This book will show you. It's not a primer or a technical manual; it's an introduction. It's your friend Ivo, waving you over at a cocktail party and saying "Hey, this is Red. I think you two might get along. Red is..." and runs down Red's C.V. while throwing in a few saucy details to pique your interest.
The more you talk to Red, the more it opens your mind to new ways of thinking. That's your job, remember? Thinking and solving problems. Writing code is, or should be, incidental. Sadly, the complexity of modern software development has turned things upside down, while simultaneously sucking the fun out of making software. Red wants to change that, and this book will help you get started.
Red will seem familiar, but also strange. It's approachable, but technically advanced. There's nothing quite like it (except its predecessor, Rebol, of course). One minute you're using it as a scripting language, the next it's cross-compiling your reactive GUI application, from your current environment, with C-level speed extensions, into stand-alone executables, each about 1 MB in size. You look like a superhero, but your sidekick is the one doing all the work.
Or maybe you thought we don't need any new languages.
Gregg Irwin
Red Community Manager Head of the Operational Team of the Red Language Foundation
Ivo Balbaert is a former lecturer for (Web) programming and databases at CVO Antwerpen, a community college in Belgium. He received a PhD in applied physics from the University of Antwerp in 1986. He worked for 20 years in the software industry as a developer and consultant in several companies, and for 10 years as a project manager at the University Hospital of Antwerp. Since 2000, he has been partly teaching, developing software, and writing technical books, among others:
Rust Essentials
Getting Started with Julia
The Way to Go
Rudolf Meijer wrote his first computer program in 1966. He was involved in the creation and formal definition of several programming languages, notably CHILL and Ada. He has programmed in Fortran II and IV, COBOL, Turbo Pascal, Visual Basic, Euphoria, Rebol, and now Red. He has contributed to the development of Rebol and is now strongly involved with Red, having published a formal specification of Red/System and preparing one for Red itself.
If you're interested in becoming an author for Packt, please visit authors.packtpub.com and apply today. We have worked with thousands of developers and tech professionals, just like you, to help them share their insight with the global tech community. You can make a general application, apply for a specific hot topic that we are recruiting an author for, or submit your own idea.
Title Page
Copyright and Credits
Learn Red – Fundamentals of Red
Dedication
Packt Upsell
Why subscribe?
PacktPub.com
Foreword
Contributors
About the author
About the reviewer
Packt is searching for authors like you
Preface
Who this book is for
What this book covers
To get the most out of this book
Download the example code files
Conventions used
Get in touch
Reviews
Red's Mission
Technical requirements
A short history of Red
What Red stands for
Some history
What makes Red special?
A full-stack language – from the metal to the meta
Code is data and data is code
Data types built in
Small toolchain and executables
Dialects
Red's main features
Portability
Like a Swiss Army knife
Summary
Questions
Setting Up for Development
Technical requirements
Installing Red
Installing Red on Windows
Installing Red on Linux and macOS
A look at the source code
Working interactively in the Red console
Running and compiling your first script
Executing a script in the Red console
Compiling a script to an executable
Development mode
Release mode
Other compilation options
Red's compilation model
Development environments for writing Red
Simple text editors
More sophisticated editors
Summary
Questions
Using Words, Values, and Types
Technical requirements
Understanding words and values
Some common datatypes
Using blocks and parens
Comments
Word bindings
Inferring types
Assigning and copying
Working with words
More about types
Converting types
The type system
Evaluating expressions and blocks
Some basic operations
Working with Boolean values
Working with numbers
Making random objects
Order of evaluation
Evaluation with do and reduce
The structure of a Red program
Summary
Questions
Further reading
Code-Controlling Structures
Technical requirements
Getting input from the user – input and ask
Testing conditions
if  
unless
either 
Stopping a program – halt or quit
switch and case
catch and throw
Structuring repetitions
Repeating a number of times – loop or repeat
Repeating with a condition – while or until
A number-guessing game
Handling errors
attempt and try
Using error?
Creating and catching errors
Checking types
Summary
Questions
Working with Series and Blocks
Technical requirements
Series and blocks
Navigating and looping through a series
A step at a time – head, tail, index?, and next
Looping through a series – foreach and forall
Getting information from a series
Selecting an item – pick and /
Searching for an item – select and find
Sorting
Changing a series
Changing items – poke, replace, and change
Adding new items – append, repend, and insert
append
repend
insert
Deleting items – remove and take
Moving items – move and swap
Series as sets
Copying a series
Strings as series
Splitting a string – split
Turning a series into a string – form
Rejoining a block – rejoin
Clearing part of a string – clear and trim
Adding to a string – append and insert
Other useful tricks
Summary
Questions
Using Functions and Objects
Technical requirements
A fauna of functions
The do word
The does word
The has word
The func word
The function word
Copying a local series
Function attributes
Passing arguments
Typing arguments
Return values – return and exit
Refinements
Code style and documentation strings
Working with functions
Error handling
Recursive functions
Importing functions with do
Code is data and data is code
Using reflection on functions
The source word
The body-of function
Changing the header and body of a function through code
Code is just data – load
Using objects
The make word
Working with objects
Creating objects
Working with fields and functions
Copying objects and inheritance
Looking inside an object
Summary
Questions
Working with Files
Technical requirements
Selecting a file or folder
Working with file paths and directories
Reading and writing data files
Working with binary files
The image! datatype
Downloading a file from the internet 
Loading and saving files
Saving and loading the console history
Downloading currency exchange rates
Using query string parameters
Summary
Questions
Parsing Data
Technical requirements
The bitset! datatype
Understanding how parse works
First parse examples
Using some and any
Matching positions
Choosing with |
Searching, extracting, and changing
Working with variables – to, thru, and copy
Executing code on a match
Changing data – change, remove, and insert
More features and examples
Using end
Building special languages
Changing a rule on the fly
Parsing blocks and code
Debugging parse
Summary
Questions
Composing Visual Interfaces
Technical requirements
Structuring an interface
First example – a screen for downloading exchange rates
Running the example
Examining the code
Building a layout
Faces and actions
Two-way binding
Container settings – view
Changing an app's icon
View's refinements
Using do in view
Layout commands
A faces walkthrough
Base, box, and image
Text faces – h1, text, field, and area
Button, check, and radio
List faces – text-list, drop-list, and drop-down
Panel, group-box, and tab-panel
Progress bar and slider
Styles
Events and actors
Multiple events
Timer event
Actors are objects
Detecting the keyboard
Menus
Basic contacts app
An introduction to the draw dialect
Summary
Questions
Further reading
Advanced Red
Technical requirements
Reactive programming
Red/System
Comparing Red and Red/System
Calling a Red/System script from within Red
Interacting with the operating system
Getting input from command-line arguments
Calling an external program – call
Using the OS clipboard – read-clipboard
Datatypes for performance
The vector! datatype
The map! and hash! datatypes
Embedded Red and macros
Embedded Red
Macros
Red for smart contract programming
Red/C3 
Using Red for writing dapps
Red's roadmap
Some useful references
Summary
Questions
Further reading
Assessments
Other Books You May Enjoy
Leave a review - let other readers know what you think
This book is about the Red programming language and environment. It highlights its specific features, such as its compactness and full-stack capabilities. Red is different from other languages. It approaches programming differently and perhaps doesn't have all the shiny things from most mainstream languages that you come to expect. Rather, it gives you better tools for thought and for getting your job done. This book will give you a head start with this new inspiring technology.
The book is ready for the 0.6.4 version. All code examples have been tested under this release.
This book is aimed at software developers and architects who want to learn Red because of its conciseness, flexibility, expressiveness, and more specifically, for its possibilities in GUI apps and blockchain/smart contract programming. Some knowledge of the basic concepts and experience of any programming language is assumed.
Chapter 1, Red's Mission, talks about the main characteristics of Red and motivates the reader to embark on their Red journey.
Chapter 2, Setting Up for Development, teaches the reader how to install Red on their system and start working with the Red console and with code files in a development environment.
Chapter 3, Using Words, Values, and Types, takes a look at the basic building blocks of a Red program—words and values. We discuss the different types available in Red.
Chapter 4, Code-Controlling Structures, focuses on how blocks, values, and words are evaluated through conditions, loop structures, and selections. This chapter also shows you how to do error handling in Red. We illustrate this throughout the chapter by developing a guessing-number game.
Chapter 5, Working with Series and Blocks, helps you to understand that blocks and series form the foundation of Red code. Developing in Red primarily means working with blocks, so that's what we will learn.
Chapter 6, Using Functions and Objects, deals with how to make your code more compact and readable using of functions and objects.
Chapter 7, Working with Files, helps you learn how to use files as a data store. We examine reading and writing files, either data files or code files. We'll develop the topic through an ongoing example of downloading currency exchange rates.
Chapter 8, Parsing Data, explores a first Red dialect called parse, which is specialized in analyzing data streams. We apply it to get meaningful information from the currency rates we stored previously.
Chapter 9, Composing Visual Interfaces, introduces a second Red dialect to build cross-platform graphical user interfaces. It builds upon Chapter 5, Working with Series and Blocks, and Chapter 7, Working with Files, to build a visual frontend for our exchange rate download, and we'll also develop a basic contacts data store app.
Chapter 10, Advanced Red, encounters the power of reactive programming to build highly reactive apps. You will get an idea of the foundational layer of it all, namely Red/System. Furthermore, you get to know how to interact with the operating system and use some high-performance datatypes. Also, Red's future in the blockchain programming world is discussed. Finally, we discuss what lies ahead of us, and provide some pointers to deepen the readers' Red knowledge.
Some knowledge of the basic concepts of programming and a bit of experience of any programming language, such as Java, C#, Python, Ruby, or JavaScript, is assumed. To follow along with the examples and exercises, only a minimal install is required, which is discussed in detail in Chapter 2, Setting Up for Development. Practice is the best way to learn a new language. That's why each chapter contains some questions and small exercises to try out your new skills. You'll find the solution in the code files and in the Assessments section.
You can download the example code files for this book from your account at www.packtpub.com. If you purchased this book elsewhere, you can visit www.packtpub.com/support and register to have the files emailed directly to you.
You can download the code files by following these steps:
Log in or register at
www.packtpub.com
.
Select the
SUPPORT
tab.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box and follow the onscreen instructions.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR/7-Zip for Windows
Zipeg/iZip/UnRarX for Mac
7-Zip/PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Learn-Red-Fundamentals-of-Red. In case there's an update to the code, it will be updated on the existing GitHub repository.
We also have other code bundles from our rich catalog of books and videos available at https://github.com/PacktPublishing/. Check them out!
Feedback from our readers is always welcome.
General feedback: Email [email protected] and mention the book title in the subject of your message. If you have questions about any aspect of this book, please email us at [email protected].
Errata: Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you have found a mistake in this book, we would be grateful if you would report this to us. Please visit www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details.
Piracy: If you come across any illegal copies of our works in any form on the Internet, we would be grateful if you would provide us with the location address or website name. Please contact us at [email protected] with a link to the material.
If you are interested in becoming an author: If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, please visit authors.packtpub.com.
Please leave a review. Once you have read and used this book, why not leave a review on the site that you purchased it from? Potential readers can then see and use your unbiased opinion to make purchase decisions, we at Packt can understand what you think about our products, and our authors can see your feedback on their book. Thank you!
For more information about Packt, please visit packtpub.com.
In this chapter, we take a look at the main characteristics of Red, more specifically, what makes Red stand out compared to other programming languages. This will motivate you to start learning Red. Don't worry if some statements are a bit abstract at this stage; they will become clearer when we start using Red in the following chapters. It may be a good idea to come back to this chapter later.
We will cover the following topics:
A short history of Red
What makes Red special?
Red's main features
You can find the code for this chapter here: https://github.com/PacktPublishing/Learn-Red-Fundamentals-of-Red/tree/master/Chapter01
Red is an open source, modern programming language and platform, designed and developed by Nenad Rakocevic. Red started out in early 2011 and is now at Version 0.6.3 (with 0.6.4 coming in the near future), aiming for a 1.0 release in the next year or so. In order to better understand its features, we have to explore its name and history a bit.
Red is short for Red[uced] REBOL, and that's why Red users proudly call themselves reducers. This points to two things:
Red builds upon REBOL, a language
that gained some fame around the millennium and was built
by Carl Sassenrath. In fact, Red is syntactically and semantically a 95% clone of REBOL, but tries to improve and enhance it where possible. This also means REBOL scripts can be easily converted to Red.
Red (like REBOL) wants to reduce today's code complexity—it aims to have compact runtime environments and dependencies (around 1 MB), instead of the hundreds of MB of the Java or .NET platform.
Development of Red started out with Red/System—this is a low-level language (like C) to enable programming at the full system level. Red/System is like an older sibling—it looks very much like Red, but it is aimed at lower-level programming so it is more restricted. We'll come back to it in Chapter 10, Advanced Red.
Gradually, Red evolved this foundation, adding with each release more and more data types, actions, and functions. A REPL interactive coding console, execution on ARM processors, a parsing engine, a cross-platform GUI dialect (working on Windows and macOS, and nearing completion on Linux and Android), reactive programming, and macros are among the hallmarks of this evolution.
From January 2015, the Fullstack Technologies company was formed to continue Red's ongoing development, together with an ever-growing community of open source contributors. The company raised capital from InnovationWorks and GeekFounders (Chinese VC early-stage investors) and has its headquarters in Beijing's Silicon Valley.
In January 2018, Red joined the blockchain revolution—through an Initial Coin Offering (ICO) with its own cryptocurrency, RED (Red Community Token) token, and it gained a vast amount of new funding capital to sustain and accelerate its completion. Using its unique capabilities, a special dialect of Red called Red/C3 is being built, specifically dedicated to blockchain and smart contracts programming.
Since spring 2018, the Red project has been managed by the Red Foundation, based in Paris (France), and also led by Nenad Rakocevic. This organization will also foster a new economic model for open source projects, using the RED token to drive development.
Here we concentrate on the characteristics that sets Red apart from other contemporary programming languages.
Together with its foundation Red/System, Red forms a full-stack language—this means it can be used to develop high-level applications (domain-specific languages, graphical frontends, and high-level scripting) as well as low-level programs (embedded systems, operating systems, and device drivers), as shown in the following diagram in comparison with other languages:
It is quite unique in programming history that a single language spans the whole programming stack. This means that you as a Red developer only have to know one language from low to high level coding!
Red is a modern descendant of the venerable LISP programming language. Instead of LISP's cumbersome parenthesis usage, it has taken Logo's simplified syntax. Everything in LISP is some kind of LISt Processing, and the same goes for Red—basically all code amounts to a combination of actions on blocks, which is the Red equivalent to LISP lists.
A block is simply a grouping of values between rectangular brackets [ ], such as [7 13 42]. You'll soon see that blocks are the fundamental building unit in Red code. This has the consequence that only a minimal syntax is used to represent code as well as data.
Like LISP, it has a very powerful capacity—it is homoiconic, literallyself-representing. What this means is that Red can work with its code just as it does with its data values, because data and code are represented the same way, namely as blocks. This makes it possible for programs to write other programs, in other words, to do metaprogramming. We'll see several examples of this feature in the coming chapters.
As we will see in the next chapter, when we're setting up, the complete toolchain (compilers, standard-library, docs, and REPL) comes packaged in a minimal 1 MB file, with no installation and configuration requirements—here we can see the reduction at work! Compare this with a Java runtime, which is about 150x bigger, or the Python runtime which also is 50 times bigger.
After compilation, Red produces executables of sizes typically around 0.5 to 1 MB, with no dependencies needed. This simplifies deployment of apps into production enormously. This aspect, combined with the low memory footprint, makes Red a very appealing choice for mobile and embedded apps. A garbage collector, which will be integrated in one of the next releases, ensures that memory consumption stays low.
Coding in Red is very expressive and concise, reducing script size, in the range of KBs. This will become apparent in the coming chapters. Just as an example, to read a web page into a string page you do the following:
page: read http://www.red-lang.orgIn 2013, the Redmonk website published an article (which you can view here: http://redmonk.com/dberkholz/2013/03/25/programming-languages-ranked-by-expressiveness/) examining the expressiveness of languages. The results were summarized in the following diagram:
On the vertical axis, the number of lines of code per commit are depicted. We see that REBOL (Red's direct parent) scores very low compared to mainstream languages, indicating that fewer lines are needed in coding comparable tasks.
One of Red's greatest strengths is the ability to easily create domain-specific languages (DSLs) or dialects. These are small and optimized sub-languages designed for a specific task, such as parse for transforming text (see Chapter 8, Parsing Data), view and draw for composing graphical user interfaces (see Chapter 9, Composing Visual Interfaces), and Red/C3 for blockchain programming (see Chapter 10, Advanced Red).
As a programming language, Red embraces nearly all paradigms:
Imperative
: Providing everything needed for controlling code execution and error-handling (see
Chapter 4
,
Code Controlling Structures
and
Chapter 5
,
Working with Series and Blocks
)
Functional
: With functions as first class values (see
Chapter 6
,
Using Functions and Objects
)
Object-oriented
: Complete with inheritance, but not class-based (see
Chapter 6
,
Using Functions and Objects
)
Concurrency
: With async task support and an actor model (from v 0.9.0)
Symbolic
: Being able to manipulate its own code as if it was plain data (all chapters)
Reactive
: Included in the
GUI
(
Graphical User Interface
) system (see
Chapter 9
,
Composing Visual Interfaces
and
Chapter 10
,
Advanced Red
)
Aside from REBOL and LISP, Red has taken inspiration from the following:
Forth and Logo for its syntax
Lua, for its capabilities as an embedded language, and its
JIT
(
Just-In-Time
) compiler
Self, for its prototype object-model
Scala, for its type inference engine and compilation
Although it can be statically compiled, Red has a graphical REPL console (Read Evaluate Print Loop) like other dynamic and scripting languages, to experiment with code interactively. We will explore this console in Chapter 2, Setting Up for Development.
In contrast to REBOL, which is an interpreted language only, Red also compiles to native code through Red/System, thus achieving much better performance, something like Crystal compared to Ruby. Compared to C, at this moment Red/System is 2-4x slower.
Red runs in the Windows, Linux, Android, macOS, and FreeBSD environments in a 32-bit version (the 64-bit version is planned) with cross-compilation capability. Furthermore, it runs on ARMv5 processors and on the Raspberry Pi and Arduino boards.
The versatility of the Red platform makes it suitable for apps on the entire spectrum, such as:
High-level scripting (for example, glue code such as Lua)
Web apps
GUI desktop applications
Android apps (from Version 0.7 onward)
2D games
Data processing
Grammar parsing and constructing specialized languages
Network/system programming, IoT devices programming, robotics
In this chapter, we looked at Red's main characteristics, and examined its place among other programming languages. In the following chapter, we will set up an environment to start up our development with Red.
Why does Red have a Red/System component?
What is a full-stack language, and why is Red an example of that?
What do the the Red and LISP languages have in common?
Give three ways in which Red reduces software complexity.
What is a dialect in Red? Give some examples.
Why is Red faster than REBOL?
Name some of the environments in which Red can run.