StatisticalRethinkingJulia / TuringModels.jl

Implementations of the models from the Statistical Rethinking book with Turing.jl
https://statisticalrethinkingjulia.github.io/TuringModels.jl/
MIT License
163 stars 18 forks source link

Replace ifelse #41

Closed rikhuijzer closed 3 years ago

rikhuijzer commented 3 years ago

When using the code, I noticed that ifelse is used. This function also exists in R, and for me one of the main reasons I try to avoid R. In R, it's just a hack to get stuff done because the language isn't very expressive, and because everything has to be vectorized. Luckily, we're using Julia here, so we can use clearer syntax! :smile:

In this PR, I propose to change all occurrences of ifelse with list comprehensions.

Example

Say, we want to replace "a" with 1, and "b" with 2 in A:

julia> A = ["a", "b", "a"]
3-element Array{String,1}:
 "a"
 "b"
 "a"

We could write

julia> map(x -> ifelse(x == "a", 1, 2), A)
3-element Array{Int64,1}:
 1
 2
 1

However, it is more common (and, I think, more readable) to use a ternary expression (like in C) in combination with a list comprehension

julia> [x == "a" ? 1 : 2 for x in A]
3-element Array{Int64,1}:
 1
 2
 1
goedman commented 3 years ago

Thanks Rik!

rikhuijzer commented 3 years ago

:+1: