我最近决定学习Elixir.来自C++/Java/JavaScript背景,我在掌握基础知识方面遇到了很多麻烦.这可能听起来很愚蠢,但返回语句如何在Elixir中起作用?我环顾四周,好像它只是一个函数的最后一行,即
def Hello do
"Hello World!"
end
Run Code Online (Sandbox Code Playgroud)
这个函数会返回"Hello World!",还有另一种方法可以返回吗?另外,你怎么会早点回来?在JavaScript中,我们可以编写类似这样的内容来查找数组中是否有某个值:
function foo(a){
for(var i = 0;i<a.length;i++){
if(a[i] == "22"){
return true;
}
}
return false;
}
Run Code Online (Sandbox Code Playgroud)
如何在Elixir中起作用?
我可以在C++中轻松地做到这一点(注意:我没有测试它的正确性 - 它只是为了说明我正在尝试做什么):
const int BadParam = -1;
const int Success = 0;
int MyFunc(int param)
{
if(param < 0)
{
return BadParam;
}
//normal processing
return Success;
}
Run Code Online (Sandbox Code Playgroud)
但我无法弄清楚如何在F#早期退出例行程序.我想要做的是在输入错误时退出该功能,但如果输入正常则继续.我错过了F#的一些基本属性,还是因为我刚刚学习FP而以错误的方式解决问题?是failwith我在这里唯一的选择?
这是我到目前为止所得到的,它编译好了:
#light
module test1
(* Define how many arguments we're expecting *)
let maxArgs = 2;;
(* The indices of the various arguments on the command line *)
type ProgArguments =
| SearchString = 0
| FileSpec = 1;;
(* Various errorlevels which the app can return and …Run Code Online (Sandbox Code Playgroud) 简而言之,为什么return在Elixir和某些(大多数?全部?)功能语言中没有声明?
为了使它更长一点,我遇到了在Java,Groovy,C,Ruby中的情况……我会写一些类似的东西
def func (some, parameters) {
# say some error
if(condition 1) {
return -1
}
# execute some function and return from here the result
if(condition 2) {
return process1(params)
}
# execute 'default' behavior when no condition matches and return result
process2(params)
}
Run Code Online (Sandbox Code Playgroud)
当然,这可以写为nested,if但是如果条件列表很长,则代码将变得不可读。
我在Elixir中阅读了关于Return语句问题的答案:它们清楚地说明了如何实现这种模式,但没有解释没有这种原因的原因return。
我相信拥有return会打破某些FP概念,但我想知道哪个以及为什么。
我最近开始学习Elixir,我真的非常喜欢它,但它是我用过的第一种函数式编程语言.我遇到的问题来自于我一直在阅读教程和在LearnElixir上观看截屏视频,你应该尽量避免使用IF类型语句.
但我发现自己经常筑巢cond或case
我会用Golang或Javascript之类的其他语言解决这些解决方案,只需使用带有早期返回的if语句,这样超出该范围的代码就不会运行,这使得我不得不通过检查falsy来占用条件的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 …Run Code Online (Sandbox Code Playgroud)