简体   繁体   English

如果列入清单,那就是利弊

[英]cons erlang if stament into list

is it possible to us an if statement in a similar way to Haskell in the following structure? 我们可以在以下结构中以与Haskell类似的方式使用if语句吗?

replace_with :: (a -> Bool) -> [a] -> a -> [a]
replace_with _ [] _ = []
replace_with f (x:xs) y = (if f x then y else x) : replace_with f xs y

I have tried the following: 我尝试过以下方法:

rwith(_,[],_) ->
    [];
rwith(F,[X|XS],Y) ->
    [if F(X) == true -> Y; true -> X, end. | replace_with(F,XS,Y)].

but I get the compile response: 但是我得到了编译响应:

listsh.erl:40: syntax error before: 'end'
listsh.erl:40: syntax error before: '|'

I have used the following which works fine, but am interested in knowing if consing the return of an if statement is possible? 我使用了以下哪个工作正常,但我有兴趣知道是否有可能返回if语句?

replace_with(_,[],_) ->
    [];
replace_with(F,[X|XS],Y) ->
    case F(X) of
        true -> [Y|replace_with(F,XS,Y)];
        false -> [X|replace_with(F,XS,Y)]
    end.

Correct code should be: 正确的代码应该是:

[if F(X) =:= true -> Y; true -> X end | replace_with(F,XS,Y)].

(using =:= is more convenient in Erlang but doesn't matter here) but there can be only guard expression in if statement so you have to use (在=:= Erlang中使用=:=更方便但在这里并不重要)但if语句中只能有guard表达式所以你必须使用

T = F(X),
[if T =:= true -> Y; true -> X end | replace_with(F,XS,Y)].

or more idiomatic 或更多惯用语

[case F(X) of true -> Y; false -> X end | replace_with(F,XS,Y)].

You can even replace the whole function with 您甚至可以用。替换整个功能

[ case F(X) of true -> Y; false -> X end || X <- XS ].

Note Erlang syntax here, , is separator of expressions, ; 注意这里二郎语法,是表达式的分隔符; is separator of clauses, . 是条款的分隔符, . ends the function definition, end ends compound expression. 结束函数定义, end复合表达式。 It can be inconvenient for someone who comes from other languages. 对于来自其他语言的人来说可能不方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM