ebook img

Nim in Action PDF

324 Pages·2017·14.34 MB·English
Save to my drive
Quick download
Download
Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.

Preview Nim in Action

Dominik Picheta M A N N I N G Nim Reference Common constructs const x = 5 Compile-time constant let y = “Hello” Immutable binding var z = [1, 2, 3] Mutable variable proc name(param: int): ReturnType = body method name(param: float): ReturnType = body iterator items(list: seq[int]): int = body template name(param: typed) = body macro name(param: string): untyped = body if x > 5: case x body of 5: elif y == "Hello": body body of 1, 2, 3: body else: of 6..30: body body for item in list: for i in 0..<len(list): body body while x == 5: try: if y.len > 0: raise err break except Exception as exc: else: echo(exc.msg) continue finally: discard Input/Output echo(x, 42, "text") readFile("file.txt") stdout.write("text") writeFile("file.txt", "contents") stderr.write("error") open("file.txt", fmAppend) stdin.readLine() Type definitions type type type MyType = object Colors = enum MyRef = ref object field: int Red, Green, field*: string Blue, Purple Licensed to <null> Nim in Action Licensed to <null> Licensed to <null> Nim in Action DOMINIK PICHETA MANNING SHELTER ISLAND Licensed to <null> For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 761 Shelter Island, NY 11964 Email: [email protected] ©2017 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Development editors: Cynthia Kane, Dan Seiter, Marina Michaels Technical development editor: Andrew West Manning Publications Co Review editor: Donna Clements 20 Baldwin Road Project editor: Karen Gulliver PO Box 761 Copyeditor: Andy Carroll Shelter Island, NY 11964 Proofreader: Katie Tennant Technical proofreader: Michiel Trimpe Typesetter: Dottie Marsico Cover designer: Marija Tudor ISBN 9781617293436 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – EBM – 22 21 20 19 18 17 Licensed to <null> contents preface xi acknowledgments xii about this book xiv about the author xvii about the cover illustration xviii PART 1 THE BASICS OF NIM...........................................1 1 Why Nim? 3 1.1 What is Nim? 4 Use cases 4 ■ Core features 6 ■ How does Nim work? 11 1.2 Nim’s benefits and shortcomings 12 Benefits 12 ■ Areas where Nim still needs to improve 20 1.3 Summary 20 2 Getting started 22 2.1 Nim syntax 22 Keywords 23 ■ Indentation 23 ■ Comments 25 2.2 Nim basics 25 Basic types 25 ■ Defining variables and other storage 30 Procedure definitions 33 2.3 Collection types 39 Arrays 39 ■ Sequences 41 ■ Sets 42 v Licensed to <null> vi CONTENTS 2.4 Control flow 43 2.5 Exception handling 47 2.6 User-defined types 49 Objects 49 ■ Tuples 50 ■ Enums 51 2.7 Summary 53 PART 2 NIM IN PRACTICE.............................................55 3 Writing a chat application 57 3.1 The architecture of a chat application 58 What will the finished application look like? 58 3.2 Starting the project 61 3.3 Retrieving input in the client component 63 Retrieving command-line parameters supplied by the user 63 Reading data from the standard input stream 66 Using spawn to avoid blocking input/output 68 3.4 Implementing the protocol 70 Modules 71 ■ Parsing JSON 72 ■ Generating JSON 78 3.5 Transferring data using sockets 79 What is a socket? 82 ■ Asynchronous input/output 83 Transferring data asynchronously 91 3.6 Summary 100 4 A tour through the standard library 101 4.1 A closer look at modules 103 Namespacing 105 4.2 Overview of the standard library 107 Pure modules 107 ■ Impure modules 108 Wrappers 108 ■ Online documentation 108 4.3 The core modules 110 4.4 Data structures and algorithms 111 The tables module 112 ■ The sets module 114 The algorithms 115 ■ Other modules 117 4.5 Interfacing with the operating system 117 Working with the filesystem 118 ■ Executing an external process 120 ■ Other operating system services 122 Licensed to <null> CONTENTS vii 4.6 Understanding and manipulating data 122 Parsing command-line arguments 122 4.7 Networking and the internet 126 4.8 Summary 127 5 Package management 128 5.1 The Nim package manager 129 5.2 Installing Nimble 130 5.3 The nimble command-line tool 131 5.4 What is a Nimble package? 131 5.5 Installing Nimble packages 135 Using the install command 135 ■ How does the install command work? 136 5.6 Creating a Nimble package 139 Choosing a name 139 ■ A Nimble package’s directory layout 140 ■ Writing the .nimble file and sorting out dependencies 141 5.7 Publishing Nimble packages 145 5.8 Developing a Nimble package 147 Giving version numbers meaning 147 ■ Storing different versions of a single package 147 5.9 Summary 148 6 Parallelism 150 6.1 Concurrency vs. parallelism 151 6.2 Using threads in Nim 153 The threads module and GC safety 153 ■ Using thread pools 156 ■ Exceptions in threads 159 6.3 Parsing data 159 Understanding the Wikipedia page-counts format 160 Parsing the Wikipedia page-counts format 161 Processing each line of a file efficiently 164 6.4 Parallelizing a parser 168 Measuring the execution time of sequential_counts 168 Parallelizing sequential_counts 168 ■ Type definitions and the parse procedure 169 ■ The parseChunk procedure 170 ■ The parallel readPageCounts procedure 171 The execution time of parallel_counts 172 Licensed to <null> viii CONTENTS 6.5 Dealing with race conditions 173 Using guards and locks to prevent race conditions 174 Using channels so threads can send and receive messages 176 6.6 Summary 179 7 Building a Twitter clone 180 7.1 Architecture of a web application 181 Routing in microframeworks 183 ■ The architecture of Tweeter 185 7.2 Starting the project 186 7.3 Storing data in a database 189 Setting up the types 190 ■ Setting up the database 192 Storing and retrieving data 194 ■ Testing the database 198 7.4 Developing the web application’s view 200 Developing the user view 204 ■ Developing the general view 207 7.5 Developing the controller 210 Implementing the /login route 212 ■ Extending the / route 214 ■ Implementing the /createMessage route 215 Implementing the user route 216 ■ Adding the Follow button 217 ■ Implementing the /follow route 218 7.6 Deploying the web application 219 Configuring Jester 219 ■ Setting up a reverse proxy 219 7.7 Summary 221 PART 3 ADVANCED CONCEPTS....................................223 8 Interfacing with other languages 225 8.1 Nim’s foreign function interface 226 Static vs. dynamic linking 227 ■ Wrapping C procedures 228 Type compatibility 231 ■ Wrapping C types 231 8.2 Wrapping an external C library 234 Downloading the library 235 ■ Creating a wrapper for the SDL library 235 ■ Dynamic linking 236 Wrapping the types 237 ■ Wrapping the procedures 238 Using the SDL wrapper 240 Licensed to <null>

Description:
Summary Nim is a multi-paradigm language that offers powerful customization options with the ability to compile to everything from C to JavaScript. In Nim in Action you'll learn how Nim compares to other languages in style and performance, master its structure and syntax, and discover unique feature
See more

The list of books you might like

Most books are stored in the elastic cloud where traffic is expensive. For this reason, we have a limit on daily download.