DEV Community

Thanabodee Charoenpiriyakij
Thanabodee Charoenpiriyakij

Posted on

3 1

หัด Erlang and Elixir v0.2.0 - variable

การสร้างตัวแปรใน Erlang นั้นจะใช้ชื่อตัวแปรขึ้นต้นด้วยตัวอักษรตัวใหญ่

1> Greeting = "hello".
"hello"
2> Greeting.
"hello"

ใน Erlang นั้นจำเป็นต้องใช้ . เป็นตัว end statement เสมอ และ assign ให้ตัวแปรเดิมทับไม่ได้

3> Greeting = "new hello".
** exception error: no match of right hand side value "new hello"

NOTE: ใน Erlang shell เราสามารถทำยกเลิก variable binding ได้ด้วยการใช้ function f() เช่น

4> f(Greeting).
ok
5> Greeting = "new hello".
"new hello"

ส่วนของ Elixir นั้นใช้ขึ้นด้วยตัวเล็ก

iex(1)> greeting = "hello"
"hello"
iex(2)> greeting
"hello"

แถมต่างกับ Erlang ตรง assign ทับได้

iex(3)> greeting = "new hello"
"new hello"
iex(4)> greeting
"new hello"

แต่ถ้าอยากไม่ให้ re-assign ค่าใหม่ที่ไม่ใช่ค่าเดิมได้ จะต้องใช้ ^ นำหน้าตัวแปร Elixir จะทำการ match value ระหว่างสองข้างให้

iex(5)> ^greeting = "hello"
** (MatchError) no match of right hand side value: "hello"
    (stdlib) erl_eval.erl:453: :erl_eval.expr/5
    (iex) lib/iex/evaluator.ex:257: IEx.Evaluator.handle_eval/5
    (iex) lib/iex/evaluator.ex:237: IEx.Evaluator.do_eval/3
    (iex) lib/iex/evaluator.ex:215: IEx.Evaluator.eval/3
    (iex) lib/iex/evaluator.ex:103: IEx.Evaluator.loop/1
    (iex) lib/iex/evaluator.ex:27: IEx.Evaluator.init/4
iex(5)> ^greeting = "new hello" # สามารถ assign ได้เพราะค่าทางด้านขวาเป็นค่าเดียวกับด้านซ้าย
"new hello"

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay