I know that it is rather a common pattern in many programming languages (predominantly functional) but I don't know exactly how does it call. So I have one data structure e.g. List A and other List B. List A contains some values (strings in Chinese) and I want to map this strings to List B translating them to English. The so called map and mutate. Can someone please tell how does this pattern named correctly and give some links to its implementation in objective-C , Java , Haskell, etc.
This process is referred to as "mapping" or "map and mutate" (as you mentioned) and data types which can be mapped over can be instances of the Functor typeclass in Haskell (note that "functor" is used differently in C++). Additionally, in imperative languages, this process may be accomplished using a foreach-style loop.
Many functional language provide a default implementation of map for lists, and may provide default implementations for other data types as well. For example, the Haskell implementation of mapping over lists is:
map :: (a -> b) -> [a] -> [b]
map _ [] = []
map f (x:xs) = f x : map f xs
chineseToEnglish :: [String] -> [String]
chineseToEnglish chineseStrings = map translate chineseStrings
More complex examples exist for more complex data structure. Try searching your favorite data structure on Hoogle and looking at the source.
While, in imperative languages, 3-element for loops provide the standard way to iterate over arrays, C++11, Java, and Obj-C all have more map-related for loops as well.
C++11 provides an abstraction over iterators in its new ranged-for loop:
vector<string> chinese;
for (auto &s : chinese) {
translate(s);
}
Extending the iterator class has been explained elsewhere
Java provides a similar construct, but without automatic type inference or the need for explicit references:
ArrayList<LanguageString> chinese = new ArrayList();
for (LanguageString s : chinese) {
s.translate();
}
Extending Iterable has also been explained elsewhere.
I'm not as familiar with Obj-C as the others I've mentioned, but that subject appears to have been discussed thoroughly at this SO post.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With