ทำความเข้าใจ Capture Operator (&) ในภาษา Elixir

Elixir Jun 3, 2023

ช่วงนี้ผมกำลังหัดเขียน Elixir เล่นๆ ก็เลยนำมาเขียนจดบันทึกเอาไว้ละกันครับ เรื่องเกี่ยวกับ & หรือ capture operator ในภาษา Elixir ตัวบทความไม่ได้เป็น Tutorial เน้นจดเอาไว้ทวนตัวเองครับ เป็น Today I Learned (TIL)

ซึ่งตัว capture operator เป็นการ capture และ create anonymous function นั่นเอง ตามนิยามคือ

It is also possible to capture public module functions and pass them around as if they were anonymous functions by using the capture operator 
Function — Elixir v1.14.5

ตัวอย่างเช่น ใช้ String.length/1

String.length("hello")

5

เราสามารถ capture ด้วย & แบบนี้

my_string = &String.length/1
my_string.("hello")

5

ซึ่งถ้าสังเกต ตัว syntax มันจะเป็นรูปแบบ &(module_name.function_name/arity)

หรือการ capture IO.puts เพื่อ capture std out.

hi = &(IO.puts/1)
hi.("Hello!")

Hello!

อีกตัวอย่าง เช่น สมมติ มี annonymous function ธรรมดา และ assign ไปที่ sum จะประกาศแบบนี้

sum = fn a, b -> a + b end
sum.(1, 2)

3

function นี้รับ 2 arguments เราสามารถ capture โดยไม่ต้องระบุ module functions แบบนี้

sum = &(&1 + &2)
sum.(1, 2)

3

ตัว &1 หมายถึง arg ตัวที่ 1 และ &2 ก็ตัวที่ 2 ไปเรื่อยๆ ตามจำนวน arity

ตัวอย่างสุดท้าย เช่น ต้องการ double ค่าตั้งแต่ 1 ถึง 10 ใน list

Enum.map(1..10, fn x -> x * 2 end)

ก็ใช้ capture แบบนี้

Enum.map(1..10, &(&1 * 2))

หรือ capture ไปใส่ตัวแปร และเรียกแบบนี้

double = &(&1 * 2)
Enum.map(1..10, double)

# ผลลัพธ์
[2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

จบแล้ว


References

Modules and functions
Website for Elixir
Function — Elixir v1.14.5
Capture operator `&` ampersand - can always I thing about it as `fn x`?
Capture operator & ampersand - can always I thing about it as fn x? Hi Everybody, Could you please help me understand how does capture operator & (ampersand) work under the hood (Elixir or Erlang)? I went through the whole https://elixir-lang.org/getting-started/introduction.html and one thing I…

Tags

Chai Phonbopit

เป็น Web Dev ทำงานมา 10 ปีหน่อยๆ ด้วยภาษา JavaScript, Node.js, React, Vue และปัจจุบันกำลังสนใจ Web3, Crypto และ Blockchain เขียนบล็อกที่ https://devahoy.com