Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Julia: Functional Programming :Validate array entries against another array of values

I'm tying to create a one liner that filters an array against an array of values. Meaning that I want to cycle through each element of A and compare to the elements of B.

For example: What is safe to drink?

A = ["water";"beer";"ammonia";"bleach";"lemonade"]
B = ["water";"beer"; "lemonade"]

I slapped together this monstrosity but, I'm hoping someone has a more elegant approach:

julia> vcat(filter(w->length(w)!= 0, map(y->filter(z->z!="",(map(x-> begin x==y ? x = y : x = ""  end,B))),A))...)
3-element Array{String,1}:
 "water"
 "beer"    
 "lemonade"
like image 549
nominalize Avatar asked Mar 18 '20 19:03

nominalize


2 Answers

You can use filter to iterate over the available drinks and in to check whether the current element is in the list of safe drinks:

julia> drinks = ["water", "beer", "bleach"];

julia> safe = ["beer", "lemonade", "water"];

julia> filter(in(safe), drinks)
2-element Array{String,1}:
 "water"
 "beer"
like image 179
David Varela Avatar answered Nov 09 '22 01:11

David Varela


The filter approach is very neat. You can also use a comprehension:

[a for a in A if a in B]
like image 21
DNF Avatar answered Nov 08 '22 23:11

DNF