Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to filter map like array comprehension?

Tags:

julia

With arrays, you can filter based on a condition:

[i for i=1:10 if isodd(i) ]

returns:

5-element Vector{Int64}:
 1
 3
 5
 7
 9

but attempting something similar with map results in nothing values:

julia> map(1:10) do i
           isodd(i) ? i : nothing
           end

reutrns:

10-element Vector{Union{Nothing, Int64}}:
 1
  nothing
 3
  nothing
 5
  nothing
 7
  nothing
 9
  nothing
like image 566
Alec Avatar asked Oct 20 '21 02:10

Alec


People also ask

Is map a list comprehension?

List comprehension is more concise and easier to read as compared to map. List comprehension are used when a list of results is required as map only returns a map object and does not return any list. Map is faster in case of calling an already defined function (as no lambda is required).

What is the difference between map and reduce?

Generally "map" means converting a series of inputs to an equal length series of outputs while "reduce" means converting a series of inputs into a smaller number of outputs. What people mean by "map-reduce" is usually construed to mean "transform, possibly in parallel, combine serially".

What is difference between MAP filter and reduce?

map creates a new array by transforming every element in an array individually. filter creates a new array by removing elements that don't belong. reduce , on the other hand, takes all of the elements in an array and reduces them into a single value. Just like map and filter , reduce is defined on Array.


1 Answers

map is a one-to-one mapping. So I'm afraid you can't do the same with map. Maybe what you are looking for is just filter?

julia> a = 1:10
1:10

julia> filter(isodd, a)
5-element Vector{Int64}:
 1
 3
 5
 7
 9
like image 83
Jun Tian Avatar answered Sep 29 '22 07:09

Jun Tian