Search a list of records: Difference between revisions

added Factor
(added Factor)
Line 642:
IO.puts Enum.find(cities, fn city -> String.first(city[:name])=="A" end)[:population]</lang>
 
{{out}}
<pre>
6
Khartoum-Omdurman
4.58
</pre>
 
=={{header|Factor}}==
For our associative structure, we use the tuple: an object composed of named slots, each holding a value which can be accessed using automatically-generated accessors. Factor is built around combinators (Factor's word for higher-order functions), so completing the task as requested is idiomatic. <code>find</code> is an existing combinator that takes a sequence and a predicate quotation (quotation being Factor's word for anonymous function) and returns the first element of the sequence for which the predicate quotation yields <code>t</code>.
 
Not only does <code>find</code> return the element, but also the index, which allows us to use <code>find</code> for all of the required tasks. Since Factor is a stack-based concatenative language, multiple return values are elegant to use. We can simply <code>drop</code> the sequence element on the top of the data stack if we are only interested in the index, or we can <code>nip</code> the index if we are only interested in the sequence element on the top of the stack.
<lang factor>USING: accessors io kernel math prettyprint sequences ;
IN: rosetta-code.search-list
 
TUPLE: city name pop ;
 
CONSTANT: data {
T{ city f "Lagos" 21.0 }
T{ city f "Cairo" 15.2 }
T{ city f "Kinshasa-Brazzaville" 11.3 }
T{ city f "Greater Johannesburg" 7.55 }
T{ city f "Mogadishu" 5.85 }
T{ city f "Khartoum-Omdurman" 4.98 }
T{ city f "Dar Es Salaam" 4.7 }
T{ city f "Alexandria" 4.58 }
T{ city f "Abidjan" 4.4 }
T{ city f "Casablanca" 3.98 }
}
 
! Print the index of the first city named Dar Es Salaam.
data [ name>> "Dar Es Salaam" = ] find drop .
 
! Print the name of the first city with under 5 million people.
data [ pop>> 5 < ] find nip name>> print
 
! Print the population of the first city starting with 'A'.
data [ name>> first CHAR: A = ] find nip pop>> .</lang>
{{out}}
<pre>
1,808

edits