스캇 (2023) LPFP: 하스켈 함수형-프로그래밍으로 배우는 물리학

Scott Walck (2023) Learn Physics with Functional Programming

[2024-06-19] : init

:하스켈

LPFP: Code for the book Learn Physics with Functional Programming (NO_ITEM_DATA:web-readhaskelltutorial)

도서 소개 : 왜 함수형 프로그래밍과 물리학이 만나야 하는가

This book teaches you to solve physics problems using the functional programming paradigm. Ideal for first-time programmers and science aficionados alike, it introduces the Haskell programming language and encourages the writing of beautiful code to match the elegant ideas of theoretical physics.

이 책은 함수형 프로그래밍 패러다임을 사용하여 물리학 문제를 해결하는 방법을 알려줍니다. 초보 프로그래머와 과학 애호가 모두에게 이상적인 이 책은 하스켈 프로그래밍 언어를 소개하고 이론 물리학의 우아한 아이디어에 맞는 아름다운 코드를 작성하도록 장려합니다.

Early chapters cover the basics of coding in Haskell, which has a powerful system of types capable of encoding important mathematical structures in physics, like vectors, derivatives, integrals, scalar fields, vector fields, and differential equations. Later sections of the book explore Newtonian mechanics and electromagnetics—two central pillars of theoretical physics. In addition, you’ll get a deep look into source code, and discover why Haskell’s high-order functions and referential transparency serve physics so well. Along the way, you’ll learn:

초반 장에서는 벡터, 미분, 적분, 스칼라 필드, 벡터 필드, 미분 방정식 등 물리학의 중요한 수학적 구조를 인코딩할 수 있는 강력한 유형 시스템을 갖춘 하스켈 코딩의 기초를 다룹니다. 책의 후반부에서는 이론 물리학의 두 가지 중심 축인 뉴턴 역학과 전자기학을 살펴봅니다. 또한 소스 코드를 자세히 살펴보고 하스켈의 고차 함수와 참조 투명성이 물리학에 유용한 이유를 알아볼 수 있습니다. 그 과정에서 많은 것을 배우게 될 것입니다:

•How to write beautiful code that expresses fundamental physical principles -기본적인 물리적 원리를 표현하는 아름다운 코드를 작성하는 방법 •How to make graphs and animations of interesting situations -흥미로운 상황의 그래프와 애니메이션을 만드는 방법 •How to program in a language that looks like mathematics -수학처럼 보이는 언어로 프로그래밍하는 방법 •How types, high order functions, and referential transparency serve physics well -타입, 고차 함수, 레퍼런스 투명성이 물리학에 어떻게 도움이 되는가?

About the Author

Brief Contents

Contents in Detail

ACKNOWLEDGMENTS

2024 Most Promising New Textbook Award

In March 2024, Learn Physics with Functional Programming won a 2024 Most Promising New Textbook Award from the Textbook and Academic Authors Association. This award is given annually to recognize excellence in 1st edition textbooks and learning materials. 2024년 3월, 함수 프로그래밍으로 배우는 물리학은 교과서 및 학술 저자 협회로부터 2024년 가장 유망한 새 교과서 상을 수상했습니다. 이 상은 매년 초판 교과서 및 학습 자료의 우수성을 인정하기 위해 수여하는 상입니다.

Congratulations LPFP! LPFP를 축하합니다!

부록: 하스켈 설치 학습 환경 준비

APPENDIX: INSTALLING HASKELL

:하스켈 문서를 참고. 생각보다 옵션이 많기에 복잡하다.

Installing GHC

The Glasgow Haskell Compiler (GHC) is the Haskell compiler we use in this book. It is free, open source software anyone can download and install.

Installing a Text Editor

:텍스트-에디터 :편집기

Installing Gnuplot

:데이터-시각화 :인포그래픽 - 맷플롯립 그누플롯 측면에서 중요하다.

설치 한다.

$ sudo apt install gnuplot

gnuplot 를 실행

gnuplot> plot cos(x)

and a window containing a plot should pop open. Once you succeed in installing the gnuplot program, you are ready to install the Haskell gnuplot package, which lets you control gnuplot from Haskell.

Installing Haskell Library Packages

Using Cabal or Using Stack

Installing Gloss : 13장 부터

Installing Diagrams : 22장 부터

Setting Up Your Coding Environment

What We Want in a Coding Environment

INTRODUCTION : 서론

Who This Book Is For

Why Functional Programming, and Why Haskell?

About This Book

PART I A HASKELL PRIMER FOR PHYSICISTS

1 CALCULATING WITH HASKELL

A Kinematics Problem

The Interactive Compiler

Numeric Functions

Operators

Precedence and Associativity

The Application Operator

Functions with Two Arguments

Numbers in Haskell

Negative Numbers in Haskell

Decimal Numbers in Haskell

Exponential Notation

Approximate Calculation

Errors

Getting Help and Quitting

More Information

Summary

Exercises

2 WRITING BASIC FUNCTIONS

Constants, Functions, and Types

How We Talk About Functions

Anonymous Functions

Composing Functions

Variable Not in Scope Error

Summary

Exercises

3 TYPES AND ENTITIES

Basic Types

The Boolean Type

The Character Type

The String Type

Numeric Types

Function Types

Summary

Exercises

4 DESCRIBING MOTION

Position and Velocity on an Air Track Types for Physical Quantities Introducing Derivatives Derivatives in Haskell Modeling the Car’s Position and Velocity Modeling Acceleration Approximate Algorithms and Finite Precision Summary Exercises

5 WORKING WITH LISTS

List Basics Selecting an Element from a List Concatenating Lists Arithmetic Sequences List Types Functions for Lists of Numbers When Not to Use a List Type Variables Type Conversion The Length of Lists A String Is a List of Characters List Comprehensions Infinite Lists List Constructors and Pattern Matching Summary Exercises

6 HIGHER-ORDER FUNCTIONS

How to Think About Functions with Parameters Mapping a Function Over a List Iteration and Recursion Anonymous Higher-Order Functions Operators as Higher-Order Functions Combinators Predicate-Based Higher-Order Functions Numerical Integration Introducing Integrators Digital Integration Implementing Antiderivatives Summary Exercises

7 GRAPHING FUNCTIONS

Using Library Modules Standard Library Modules Other Library Modules Plotting Function Only Function and Module Function, Module, and Plot Definition Summary Exercises

8 TYPE CLASSES

Type Classes and Numbers Type Classes from the Prelude The Eq Type Class The Show Type Class The Num Type Class The Integral Type Class The Ord Type Class The Fractional Type Class The Floating Type Class Exponentiation and Type Classes Sections Example of Type Classes and Plotting Summary Exercises

9 TUPLES AND TYPE CONSTRUCTORS

Pairs Currying a Function of Two Variables Triples Comparing Lists and Tuples Maybe Types Lists of Pairs Tuples and List Comprehensions Type Constructors and Kinds Numerical Integration Redux Summary Exercises

10 DESCRIBING MOTION IN THREE DIMENSIONS

Three-Dimensional Vectors Coordinate-Free Vectors Geometric Definition of Vector Addition Geometric Definition of Scaling a Vector Geometric Definition of Vector Subtraction Geometric Definition of Dot Product Geometric Definition of Cross Product Derivative of a Vector-Valued Function Coordinate Systems Vector Addition with Coordinate Components Vector Scaling with Coordinate Components Vector Subtraction with Coordinate Components Dot Product with Coordinate Components Cross Product with Coordinate Components Derivative with Coordinate Components Kinematics in 3D Defining Position, Velocity, and Acceleration Two Components of Acceleration Projectile Motion Making Your Own Data Type Single Data Constructor Multiple Data Constructors Defining a New Data Type for 3D Vectors Possible Implementations Data Type Definition for Vec Vec Functions Summary Exercises

11 CREATING GRAPHS

Title and Axis Labels Other Labels Plotting Data Multiple Curves on One Set of Axes Controlling the Plot Ranges Making a Key Summary Exercises

12 CREATING STAND-ALONE PROGRAMS

Using GHC to Make a Stand-Alone Program Hello, World! A Program That Imports Modules Using Cabal to Make a Stand-Alone Program Using Stack to Make a Stand-Alone Program Summary Exercises

13 CREATING 2D AND 3D ANIMATIONS

2D Animation Displaying a 2D Picture Making a 2D Animation Making a 2D Simulation 3D Animation Displaying a 3D Picture Making a 3D Animation Making a 3D Simulation Summary Exercises

PART II EXPRESSING NEWTONIAN MECHANICS AND SOLVING PROBLEMS

14 NEWTON’S SECOND LAW AND DIFFERENTIAL EQUATIONS

Newton’s First Law Newton’s Second Law in One Dimension Second Law with Constant Forces Second Law with Forces That Depend Only on Time Air Resistance Second Law with Forces That Depend Only on Velocity Euler Method by Hand Euler Method in Haskell The State of a Physical System Second Law with Forces That Depend on Time and Velocity Method 1: Produce a List of States Method 2: Produce a Velocity Function Example: Pedaling and Coasting with Air Resistance Euler Method by Hand Method 1: Produce a List of States Method 2: Produce a Velocity Function Summary Exercises

15 MECHANICS IN ONE DIMENSION

Introductory Code Forces That Depend on Time, Position, and Velocity A General Strategy for Solving Mechanics Problems Solving with Euler’s Method Producing a List of States Position and Velocity Functions A Damped Harmonic Oscillator Euler Method by Hand Method 1: Producing a List of States Method 2: Producing Position and Velocity Functions Euler-Cromer Method Solving Differential Equations Generalizing the State Space Type Classes for State Spaces One More Numerical Method Comparison of Numerical Methods Summary Exercises

16 MECHANICS IN THREE DIMENSIONS

Introductory Code Newton’s Second Law in Three Dimensions The State of One Particle Solving Newton’s Second Law One-Body Forces Earth Surface Gravity Gravity Produced by the Sun Air Resistance Wind Force Force from Uniform Electric and Magnetic Fields State Update for One Particle Preparing for Animation Two Helpful Animation Functions How the Functions Work Summary Exercises

17 SATELLITE, PROJECTILE, AND PROTON MOTION

Satellite Motion State-Update Function Initial State Time-Scale Factor Animation Rate Display Function Projectile Motion with Air Resistance Calculating a Trajectory Finding the Angle for Maximum Range 2D Animation 3D Animation Proton in a Magnetic Field Summary Exercises

18 A VERY SHORT PRIMER ON RELATIVITY

A Little Theory A Replacement for Newton’s Second Law Response to a Constant Force Proton in a Magnetic Field Summary Exercises

19 INTERACTING PARTICLES

Newton’s Third Law Two-Body Forces Universal Gravity Constant Repulsive Force Linear Spring Central Force Elastic Billiard Interaction Internal and External Forces The State of a Multi-Particle System State Update for Multiple Particles Implementing Newton’s Second Law Numerical Methods for Multiple Particles Composite Functions Summary Exercises

20 SPRINGS, BILLIARD BALLS, AND A GUITAR STRING

Introductory Code Two Masses and Two Springs Forces Animation Functions Stand-Alone Animation Program Using Mechanical Energy as a Guide to Numerical Accuracy A Collision Data Representations Spring Constant and Time Step Momentum and Energy Conservation Numerical Issues Animated Results Wave on a Guitar String Forces State-Update Function Initial State Stand-Alone Program Asynchronous Animation Summary Exercises

PART III EXPRESSING ELECTROMAGNETIC THEORY AND SOLVING PROBLEMS

21 ELECTRICITY

Electric Charge Coulomb’s Law Two Charges Interacting Looking at Extremes Modeling the Situation in Haskell Summary Exercises

22 COORDINATE SYSTEMS AND FIELDS

Polar Coordinates Cylindrical Coordinates Spherical Coordinates Introductory Code A Type for Position Defining the New Type Making a Position Using a Position Displacement The Scalar Field The Vector Field Functions for Visualizing Scalar Fields 3D Visualization 2D Visualization Functions for Visualizing Vector Fields 3D Visualization 2D Visualization Gradient Visualization Summary Exercises

23 CURVES, SURFACES, AND VOLUMES

Introductory Code Curves Parameterizing Curves Examples of Curves Surfaces Parameterizing Surfaces Examples of Surfaces Orientation Volumes Summary Exercises

24 ELECTRIC CHARGE

Charge Distributions Introductory Code A Type for Charge Distribution Examples of Charge Distributions Total Charge Total Charge of a Line Charge Total Charge of a Surface Charge Total Charge of a Volume Charge Calculating Total Charge in Haskell Electric Dipole Moment Summary Exercises

25 ELECTRIC FIELD

What Is an Electric Field? Introductory Code Charge Creates an Electric Field Electric Field Created by a Point Charge Electric Field Created by Multiple Charges Electric Field Created by a Line Charge Electric Field Created by a Surface Charge Electric Field Created by a Volume Charge Scalar Integrals Scalar Line Integral Scalar Surface Integral Scalar Volume Integral Approximating Curves, Surfaces, and Volumes Approximating a Curve Approximating a Surface Approximating a Volume Summary Exercises

26 ELECTRIC CURRENT

Current Distributions Introductory Code A Type for Current Distribution Examples of Current Distributions Conservation of Charge and Constraints on Steady Current Distributions Magnetic Dipole Moment Summary Exercises

27 MAGNETIC FIELD

A Simple Magnetic Effect Introductory Code Current Creates Magnetic Field Magnetic Field Created by a Line Current Magnetic Field Created by a Surface Current Magnetic Field Created by a Volume Current Summary Exercises

28 THE LORENTZ FORCE LAW

Introductory Code Statics and Dynamics State of One Particle and Fields Lorentz Force Law Do We Really Need an Electric Field? State Update Animating a Particle in Electric and Magnetic Fields Uniform Fields Classical Hydrogen Summary Exercises

29 THE MAXWELL EQUATIONS

Introductory Code The Maxwell Equations Relationships Between Electricity and Magnetism Connection to Coulomb’s Law and Biot-Savart Law State Update Spatial Derivatives and the Curl A Naive Method The FDTD Method The Yee Cell A Type for State FDTD and the Curl State Update Animation Current Density Grid Boundary Display Function Two Helping Functions Main Program Summary Exercises

All Code in One Directory

One Way to Use Stack

Summary

BIBLIOGRAPHY

INDEX

Related-Notes

References

NO_ITEM_DATA:web-readhaskelltutorial