惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

量子位
云风的 BLOG
云风的 BLOG
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
The Hacker News
The Hacker News
Martin Fowler
Martin Fowler
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
U
Unit 42
F
Full Disclosure
H
Hackread – Cybersecurity News, Data Breaches, AI and More
Recorded Future
Recorded Future
Security Archives - TechRepublic
Security Archives - TechRepublic
阮一峰的网络日志
阮一峰的网络日志
T
Threatpost
P
Privacy International News Feed
GbyAI
GbyAI
Stack Overflow Blog
Stack Overflow Blog
MongoDB | Blog
MongoDB | Blog
I
Intezer
Recent Announcements
Recent Announcements
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
P
Privacy & Cybersecurity Law Blog
A
Arctic Wolf
博客园 - 聂微东
博客园 - 叶小钗
Cisco Talos Blog
Cisco Talos Blog
H
Help Net Security
S
Schneier on Security
Y
Y Combinator Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
The Exploit Database - CXSecurity.com
T
Tor Project blog
月光博客
月光博客
NISL@THU
NISL@THU
A
About on SuperTechFans
Spread Privacy
Spread Privacy
Blog — PlanetScale
Blog — PlanetScale
D
DataBreaches.Net
雷峰网
雷峰网
C
CXSECURITY Database RSS Feed - CXSecurity.com
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
G
Google Developers Blog
W
WeLiveSecurity
P
Palo Alto Networks Blog
The Last Watchdog
The Last Watchdog
K
Kaspersky official blog
博客园 - 司徒正美
L
LINUX DO - 热门话题
小众软件
小众软件

Hacker News

Introducing Claude Opus 4.7 Qwen Studio The Future of Everything is Lies, I Guess: Where Do We Go From Here? GitHub - SeanFDZ/macmind: Single-layer transformer in HyperTalk for the classic Macintosh Show HN: Agent-cache – Multi-tier LLM/tool/session caching for Valkey and Redis Moving a large-scale metrics pipeline from StatsD to OpenTelemetry / Prometheus GitHub - Nightmare-Eclipse/RedSun: The Red Sun vulnerability repository GitHub - SethPyle376/hiraeth: Local AWS emulator focused on fast integration testing, with SQS support, SQLite-backed state, and a debug-friendly web UI. GitHub - macOS26/Agent: Any AI, replaces Claude Code, Cursor, OpenClaw. Over 18 LLM providers (Claude, OpenAI, Gemini, Ollama, Zai, HF, Qwen) wired into a native Mac app that writes code, builds Xcode projects, bumps versions, manages git, automates Safari, use AppleScript, JS or Accessibility, extend Agent! w/ MCP Servers, run tasks from your iPhone via Messages. YouTube now lets you turn off Shorts I Made a Terminal Pager Burgers | マクドナルド公式 Commands — HackerNews CLI documentation ChatGPT for Excel PiCore - Raspberry Pi Port of Tiny Core Linux Live Nation illegally monopolized ticketing market, jury finds Google Broke Its Promise to Me. Now ICE Has My Data. Founding Engineer at Adaptional | Y Combinator CRISPR takes important step toward silencing Down syndrome’s extra chromosome GitHub - saffron-health/libretto: The AI toolkit for building reliable browser automations US v. Heppner (S.D.N.Y. 2026) no attorney-client privilege for AI chats [pdf] Unexpected €54k billing spike in 13 hours: Firebase browser key without API restrictions used for Gemini requests Retrofitting JIT Compilers into C Interpreters IPv6 – Google The Accursèd Alphabetical Clock Cybersecurity Looks Like Proof of Work Now Fragments: April 14 Cal.com Goes Closed Source: Why AI Security Is Forcing Our Decision | Cal.com - Scheduling Software for Online Bookings Laravel raised money and now injects ads directly into your agent When moving fast, talking is the first thing to break Too much Discussion of the XOR swap trick – Heather Cafe Introduction to Spherical Harmonics for Graphics Programmers The Grand Line Building a Z-Machine in the worst possible language High-Level Rust: Getting 80% of the Benefits with 20% of the Pain GitHub - duguyue100/midnight-captain: Inspired by Midnight Commander, tailored to my taste. How to build a `git diff` driver · Jamie Tanna | Software Engineer Center for Responsible, Decentralized Intelligence at Berkeley The Local Universe’s Expansion Rate Is Clearer Than Ever, but Still Doesn’t Add Up - A new synthesis of astronomical measurements confirms a persistent mismatch that could point to physics beyond current models The air throughout our homes is infused with microplastics. But there are things you can do to breathe less of them The disturbing white paper Red Hat is trying to erase from the internet – OSnews The Future of Everything is Lies, I Guess: Annoyances ‘Abhorrent’: the inside story of the Polymarket gamblers betting millions on war Productive procrastination — Max van IJsselmuiden maps, territory and LMs 447 Terabytes per Square Centimetre at Zero Retention Energy: Non-Volatile Memory at the Atomic Scale on Fluorographane Show HN: Pardonned.com – A searchable database of US Pardons 20 Years on AWS and Never Not My Job The Seasons are Wrong Artemis II crew splashes down near San Diego after historic moon mission We gave an AI a 3 year retail lease in SF and asked it to make a profit | Andon Labs How a dancer with ALS used brainwaves to perform live On filing the corners off my MacBooks Installing every* Firefox extension OpenClaw’s memory is unreliable, and you don’t know when it will break Steve Blank Nowhere Is Safe Chimpanzees in Uganda locked in vicious 'civil war', say researchers watgo - a WebAssembly Toolkit for Go linux/Documentation/process/coding-assistants.rst at master · torvalds/linux GitHub - callumlocke/json-formatter: Makes JSON easy to read. Founding Product Engineer at Bild AI | Y Combinator A compelling title that is cryptic enough to get you to take action on it GitHub - Keychron/Keychron-Keyboards-Hardware-Design: Industrial design files for Keychron keyboards and mice. 100+ models with CAD assets in STEP, DXF, DWG, and PDF. Source-available, with commercial use allowed for original compatible accessories within the license terms. [ANNOUNCE] WireGuardNT v0.11 and WireGuard for Windows v0.6 Released 1D-Chess Helium Is Hard to Replace Cooperative Vectors Introduction | Evolve Keeping a Postgres queue healthy — PlanetScale Our response to the Axios developer tool compromise Do Americans read print books, e-books or audiobooks more? The Zettelkasten Method in Obsidian: A Practical Setup Guide Artemis II Is Competency Porn and We Are Starving For It WeakC4 Flight Viz — Cockpit View A Mexican surveillance giant you’ve never heard of is now watching the U.S. border Surelock: Deadlock-Free Mutexes for Rust RISC-V 101 – what is it and what does it mean for Canonical? | Ubuntu The Problem That Built an Industry How Much Linear Memory Access Is Enough? | Solidean Investigating Split Locks on x86-64 Simplest hash functions Sybilproof reputation mechanisms (2005) [pdf] What is a property? How Complex is my Code? Static code analysis in Kotlin — tools overview Toffoli gates are all you need PGLite evangelism dcmake: a new CMake debugger UI Clojure on Fennel part one: Persistent Data Structures Fragments: April 2 Python Release Python install manager 26.1 The Life and Death of the Book Review - Liberties Introducing Database Traffic Control — PlanetScale Bitcoin miners are losing $19,000 on every BTC produced as difficulty drops 7.8% God sleeps in the minerals Building slogbox Apple Silicon and Virtual Machines: Beating the 2 VM Limit Who was “Not Even Wrong” first? Pokemon Evolution Vs Darwinian Evolution The APL Programming Language Source Code
Dabbling in Erlang, part 2: A minimal introduction
2026-05-02 · via Hacker News

It’s been a while since the last post which was a short introduction into functional programming in general and now it’s time to dive into some of the basic concepts of the language.

Single assignment & pattern matching

In Erlang we should think variables in a mathematical sense of the term, which means that once you’ve bound a variable, you cannot change its value . If you state that X is 5, then it will always be 5 (a variable is called bound if already contains a value, unbound otherwise):

Eshell V5.10.1  (abort with ^G)
> X = 5.
5
> X = 6.
** exception error: no match of right hand side value 6
> X = 5.
5

But this error is not exactly what we expected. In Erlang, the = operator does actually pattern matching (there are no LHS/RHS values). A pattern match is done like so:

Pattern = Expression

The Pattern consists of data structures that may contain both bound and unbound variables. The Expression part may contain data structures, bound variables, mathematical operations and function calls. If the pattern match succeeds, any unbound variables will be bound and the value of the expression will be returned. Using pattern matching we can extract data out of complex structures:

> {_, Name, Surname} = {person, "John", "Doe"}.
{person,"John","Doe"}
> Name.
"John"
> Surname.
"Doe"
> {_, Name, "bla"} = {person, "John", "Doe"}.
** exception error: no match of right hand side value {person,"John","Doe"}

We extract the name and surname and bound them to the Name and Surname variables. The second pattern match fails because “bla” does not equal to “Doe”.

Note that all variable names must begin with a capital letter.

But this isn’t the end. Using pattern matching we can control the execution flow of our programs and write more conscise code. Let’s say we want a function which, depending on the first argument we pass it, will print something to the screen.

Here’s how we might do this in Ruby:

def greet(inc)
  case inc
  when "Hello"   then "Hi"
  when "Goodbye" then "See you"
  else inc
  end
end

greet("Hello")   # => "Hi"
greet("Goodbye") # => "See you"
greet("blabla")  # => "blabla"

Here’s a direct port to Erlang:

greet(Inc) ->
  case Inc of
    "Hello"   -> "Hi";
    "Goodbye" -> "See you";
    _         -> Inc
  end.

We essentially use the case syntax which does pattern matching. But that’s not idiomatic Erlang; we can do better: pattern match in the head of the function clause (the part before the -> is called the head and after it comes the body).

greet("Hello")   -> "Hi";
greet("See you") -> "See you";
greet(Other)     -> Other.

A function is defined as a collection of clauses. Each clause specifies the expected argument patterns and a body of expressions to be evaluated. greet/1 is still one function but without the use of case or if statements. The name/arity notation is used to describe functions. So greet/1 means the greet function which accepts one argument. It’s worth mentioning that when the compiler creates a binary search tree with the greet clauses, so pattern matching is very efficient.

But it gets better.

Let’s say you want to calculate the area of a shape which could be either a square or a circle.

In Ruby we could define two different functions:

def area_square(side)
  side * side
end

def area_circle(radius)
  3.14 * radius * radius
end

area_square(15) # => 225
area_circle(5)  # => 78.5

or using a single function we might do:

def area(shape, x)
  if shape == :square
    x * x
  elsif shape == :circle
    3.14 * x * x
  else
    raise "Unknown shape"
  end
end

area(:square, 15) # => 225
area(:circle, 5)  # => 78.5

In Erlang we could do the following, using pattern matching and one function:

area({circle, Radius}) -> 3.14 * Radius * Radius;
area({square, Side})   -> Side * Side.

and we would use it like this:

> area({square, 15}).
225
> area({circle, 5}).
78.5
> area({wtf, 5}).
** exception error: no function clause matching area({wtf,5})

In the Erlang version, we’re defining one function with multiple clauses. We also don’t have to explicitly raise an error as we did in the Ruby version, since pattern matching will do this for us.

Note that we’re using a composite data type called a tuple (that thing inside the curly brackets). I won’t get into details here, but you will see tuples everywhere in Erlang.

It’s important to point out that a function is identified by its name and its arity. Two functions with the same name but different arity are two completely different functions that just happen to share the same name. Think of it like two people with the same first name, but different last names (ie. arity).

This means we can do this:

adder(_)       -> "I'm someone".
adder(_, _)    -> "I'm another one".
adder(_, _, _) -> "I'm yet another one".
> adder(3,2)
"I'm another one"
> adder(1)
"I'm someone"
> adder(5,6,7)
"I'm yet another one"

You can notice that we terminate each definition with a period, which means we are essentially defining a different function every time. _, like in Ruby, denotes that we don’t care about the actual values of the arguments.

Guards

Guards can be thought of as additional constraints that can be applied when pattern matching.

Let’s define a function that tells us if the given number is even or odd:

is_what(X) when X rem 2 == 0 -> even;
is_what(X) when X rem 2 /= 0 -> odd.

Notice the when <guard> part? We can use our new function like this:

is_what(3). % => odd
is_what(2). % => even

To achieve the same result in Ruby, we would do something like:

def is_what(x)
  return :even if x % 2 == 0
  :odd
end

The cool thing is that guards can also be used in function heads, case and if statements.

Essentially they provide us with a succinct way to describe what we want out of a list.

Lists

Before we can do anything cool, we must really meet the most used data structure in Erlang, the List.

Lists are the bread & butter of many functional programming languages and are very efficient data types.

The first element of the list is called the head and the rest of the list is called the tail. Using pattern matching and the cons operator (|) we can easily extract those two out of a list:

> [Head|Tail] = [1,2,3,4,5].
[1,2,3,4,5]
> Head.
1
> Tail.
[2,3,4,5]
> [A|B] = Tail.
[2,3,4,5]
> A.
2
> B.
[3,4,5]
> ["Look what I did!"|B].
["Look what I did!",3,4,5]

To illustrate the recursive definition of lists, it helps to understand that all of the following notations:

[1,2,3,4]
[1,2,3,4|[]]
[1,2|[3,4]]
[1,2|[3,4|[]]]

are simply syntactic sugar for:

[1|[2|[3|[4|[]]]]]

Note that the head of the list [1] is 1 and the tail is itself an empty list ([]).

Functional programming for real

Functions in Erlang are first-class citizens. This means we can manipulate them like any other data, passing them as arguments to other functions or making them the return values of other functions.

Let’s implement our own map/2 function. Turns out it’s very easy to do using lists and recursion:

map(F, [])    -> [];
map(F, [H|T]) -> [F(H) | map(F, T)].

Our map function accepts another function as it’s first argument and applies that function to every element in the list (ie. the second argument). It’s a high-order function.

The first definition is our base case which, when reached, the function will stop recursing and return the result. Applying a function to an empty list should return an empty list.

But what function should we pass to it? We can pass it a fun which will double the passed argument by 2. You can think of funs as anonymous functions, something like blocks in Ruby (well, not quite):

> map(fun(X) -> X*2 end, [1,2,3]).
[2,4,6]

That’s awesome! In two lines of code we created our own map function.

Let’s try passing our is_what/1 function that we defined earlier:

> F = fun(X) -> is_what(X) end.
#Fun<erl_eval.6.17052888>
> map(F, [1,2,3]).
[odd,even,odd]

Neat! Functions are first-class citizens in Erlang and we can manipulate them the same way we manipulate all other data. We can even define a function wich returns another function:

times(X) ->
  fun(Y) -> X*Y end.

We can now reuse our times/1 function:

> Double = times(2).
#Fun<hi.0.67960283>
> Double(5).
10
> Triple = times(3).
#Fun<hi.0.67960283>
> Triple(3).
9

Another common task is to filter out elements that meet a particular requirement, for example even numbers:

evens([]) ->
  [];
evens([H|T]) ->
  case H rem 2 == 0 of
    true -> [H | evens(T)];
    _    -> evens(T)
  end.

Let’s see it in action:

> hi:evens([1,2,3,4,5]).
[2,4]

Note that the order of definitions is important: each definition is evaluated from top to bottom, so if we wanted to add a clause to report back whatever invalid shape was received, we might do:

area(Other)            -> {unknown, Other};
area({circle, Radius}) -> 3.14 * Radius * Radius;
area({square, Side})   -> Side * Side.

But this would not work as expected, since the first clause would always match whatever argument we passed to area/1. The following demonstrates:

> area({shapeFromSpace, 5}).
{unknown,{shapeFromSpace,5}}
> area({circle, 5}).
{unknown,{circle,5}}
> area({rectangle, 5}).
{unknown,{rectangle,5}}

To fix this we have to move the first clause to the bottom, in order to match only unknown shapes:

area({circle, Radius}) -> 3.14 * Radius * Radius;
area({square, Side})   -> Side * Side;
area(Other)            -> {unknown, Other}.

List comprehensions

It’s a very common pattern to map and filter lists. In other words to apply a function to every element of a list and from the resulting list, select those elements that meet a given requirement. List comprehensions provides us with a notation to achieve this result in a succinct yet powerful way.

Let’s say we want to pick all even numbers in a list and multiply them by 2. List comprehensions to the rescue:

> [X*2 || X <- [1,2,3,4,5], X rem 2 == 0].
[4,8]

Lists comprehensions are essentially tools to build and modify lists and are based on the set-builder notation.

That’s a fairly simple example. Let’s try something slightly more advanced by using multiple generators (ie. the part after the ||):

> [{X,Y} || X <- lists:seq(1,4), X rem 2 == 0, Y <- lists:seq(X,4)].
[{2,2},{2,3},{2,4},{4,4}]

Here the expression is the tuple {X, Y}, then follows the generator X <- lists:seq(1,4) which essentially means "X comes from lists:seq(1,4)" (lists:seq/2 is a built-in function that generates a sequence of integers), then follows the guard X rem 2 == 0 and finally another generator.

As we can see, list comprehensions result in more succinct and idiomatic code.

That’s not all folks

In this short journey, we ran into lists, pattern matching, guards, functions and list comprehensions. What we learned can be summarized as follows:

  • List is the most useful data structure in Erlang. Common operations on them are very efficient: extracting the head or tail of a list and inserting an element at the beginning of the list are constant time operations. The cons operator is the basic tool for manipulating lists.

  • Pattern matching is a fundamendal characteristic of the language and a very powerful concept that is everywhere in Erlang programs. It results in more readable code (vs if-else statements). Guards are a great tool that provide additional power to pattern matching.

  • Functions are first-class citizens and are treated like any other data type. You can pass them as arguments, assign them to variables and use them as the return values of other functions.

This was a minimal introduction to some of the basic concepts of Erlang. The next post will be about the concurrency features of the language.

Discuss this post on HackerNews.