我最近開始學習Elixir,我非常享受它,但它是我用過的第一個函數式編程語言。我面臨的問題來自我一直在閱讀的教程,並且在LearnElixir上觀看屏幕錄像是您應該儘量避免使用IF
類型的陳述。如何在函數式編程語言中使用函數而不是早期返回
但我發現自己經常築巢cond
或case
我會解決像Golang或JavaScript等語言這些解決方案通過只是使用if statment以早日迴歸,讓超越該代碼將無法運行,這阻止了我99%的時間必須通過檢查falsy值並返回來嵌套條件。
因此,在Elixir
(或其他函數式編程語言)中,如何在不使用嵌套的情況下以適當的方式編寫如下所示的內容,並利用語言的功能。
def loginPost(conn, %{"user" => user_params}) do
# Look for user in database
query = from u in User,
where: u.email == ^user_params["email"],
select: [u.email, u.username, u.password]
data = Repo.all(query)
# Check to see if a user had been found
case (length data) == 0 do
true -> # No user was found, send an error message
conn
|> json(%{ success: false, errors: ["Wrong username or password"]})
false -> # A user was found, compare password
[[email, username, db_password]] = data
case Comeonin.Bcrypt.checkpw(user_params["password"], db_password) do
true -> # Password was correct, set session and return a json response
conn
|> put_session(:authenticated, true)
|> put_session(:username, username)
|> put_session(:email, email)
|> json(%{success: true}) # Send json response and redirect on client side
false -> # Password was incorrect, send an error message
conn
|> json(%{success: false, errors: ["Wrong username or password"]})
end
end
end
end
我對如果應該避免的原因更加好奇......它根本沒有意義。在任何語言中,分支都是程序的基石。在一個非平凡的程序中必然會出現某種分支。 – HuStmpHrrr
@HuStmpHrrr我在Elixir的IRC/Slack上討論過的一些人通常會這樣說,如果我太嵌套了,我想我在一個函數中做了太多的事情,並且會寫另一個 – Datsik
這是別的東西。它適用於所有語言,即避免過多的嵌套結構。在fp中,沒有循環結構,所以批評者都指向分支。我明白了這一點。它更多的是模塊化。不僅僅是出於某種原因避免了某些特定的結構。如果使用if語句,我認爲這段代碼會更好。 – HuStmpHrrr