Reputation: 5759
is it possible to us an if statement in a similar way to Haskell in the following structure?
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?
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.
Upvotes: 1
Views: 75
Reputation: 26121
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
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. It can be inconvenient for someone who comes from other languages.
Upvotes: 4