I’ve got an Erlang snippet here that I’d like to work into more idiomatic Erlang, rather than a crude Python translation.
Process takes a pairs of congruent lists and combines them. Some of the elements need to be taken from one lists or the other, based on their properties, while the rest of the elements need to be summed. It works properly, but I get the feeling it’s not idiomatic…
Process = fun([RockA, FishA, TreeA, BarkA, DogA, CowA, MooA, MilkA, CheeseA, BreadA, WineA, GrapesA], [RockB, FishB, TreeB, BarkB, DogB, CowB, MooB, MilkB, CheeseB, BreadB, WineB, GrapesB]) ->
if
RockA /= [0,0,0] ->
NewRock = RockA,
NewFish = FishA,
NewTree = TreeA,
NewBark = BarkA,
NewDog = DogA;
true ->
NewRock = RockB,
NewFish = FishB,
NewTree = TreeB,
NewBark = BarkB,
NewDog = DogB
end,
if
CowA > CowB ->
NewCow = CowA;
true ->
NewCow = CowB
end,
NewMoo = MooA + MooB,
NewMilk = MilkA + MilkB,
NewCheese = CheeseA + CheeseB,
NewBread = BreadA + BreadB,
NewWine = WineA + WineB,
NewGrapes = GrapesA + GrapesB,
[NewRock, NewFish, NewTree, NewBark, NewDog, NewMoo, NewMilk, NewCheese, NewBread, NewWine, NewGrapes];
(_,_) ->
ok
end.
Here are some suggestions. But it’s a matter of taste whether you like the intermediate variable assignments. Just be aware the ‘case’ and ‘if’ are expressions that always evaluate to something. I’ve also removed the “(,) -> ok” catch all; this appears to be defensive programming which is discouraged in Erlang.
Or even…