gpt4 book ai didi

functional-programming - 如何在函数式编程语言中使用函数而不是提前返回

转载 作者:行者123 更新时间:2023-12-04 00:18:07 25 4
gpt4 key购买 nike

我最近开始学习Elixir我真的很喜欢它,但它是我使用过的第一种函数式编程语言。我面临的问题来自于我在 LearnElixir 上阅读教程和观看截屏视频的内容。是你应该尽量避免使用 IF 类型的语句。

但我发现自己经常嵌套 condcase

我会用 Golang 或 Javascript 等其他语言来解决这些解决方案,方法是仅使用带有提前返回的 if 语句,这样超出该条件的代码就不会运行,这使我在 99% 的情况下不必嵌套条件语句只是检查虚假值并返回。

那么在 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

最佳答案

一种方法是使用with。您可以创建单独的函数,看起来像这样:

def authenticate(email, password) do
with {:ok, user} <- find_user(email),
{:ok, user} <- validate_password(user, password),
{:ok, user} <- validate_preconditions(user)
do: {:ok, user}
end

defp find_user(email) do
# return {:ok, user} if user is found, return {:error, :user_not_found} otherwise
end

defp validate_password(user, password) do
# return {:ok, user} if password is correct, return {:error, :invalid_password} otherwise
end

defp validate_preconditions(user) do
# return {:ok, user} if user is not banned or whatever, return {:error, :cant_be_logged_in} otherwise
end

然后你可以像这样在你的 Controller 函数中使用它:

def loginPost(conn, %{"user" => user_params}) do
case authenticate(user_params["email"], user_params["password"]) do
{:ok, user} -> # start session
{:error, error_type} -> # handle error
end
end

这个例子可能会更好,但你明白了。

您还可以阅读此 question 中的答案

关于functional-programming - 如何在函数式编程语言中使用函数而不是提前返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36819196/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com