#flatMap
Explore tagged Tumblr posts
not-toivo · 7 months ago
Text
So, a single method call to flatMap is consistently slower than two method calls, to filter, and then map? The difference persists on smaller arrays (meaning, before the JIT compiler kicks in), see the last picture for an array of length 100. Not what I expected.
I guess, the lessons here are "don't be clever" and "avoid premature optimization".
Tumblr media Tumblr media Tumblr media
6 notes · View notes
notarealwelder · 1 year ago
Text
(Epistemic status: armchair theorizing)
Really, the hard part of monad explanations is not the idea of a monad. The heart of a monad fits into a sentence, and idiom of monadic code, into a paragraph! The question is rather of why: what's the point of monads? Why write code this way? How is all that useful, what problem does it solve, why that and not any other alternative?
I think this might be the question that often hangs unanswered in all the dissatisfied comments to monad tutorials; the question of motivation. And it is kind of tricky to answer, because (I claim) the principal use of monads and monadic code is to make it tenable to encode effects in type signatures. It's an important problem to solve, and it lets us write code with type-encoded side effects about as easily as ordinary imperative code with unchecked effects — a strict improvement, in principle — but...The solved problem is not directly related to the added capability; monads mitigate the inconvenience, not enhance capabilities directly. And the inconvenience is absent from the normal programming practice! Effects just happen, compiler sees them not, and composition is trivial. So the benefits are obvious from the assumption "all side effects are type-encoded" — >>= just collapses the boilerplate of manually composing consecutive effects, who wouldn't want that — but not otherwise, and it's kind of weird to answer "why monads?" with "actually the thing you want is type-encoded effects; monads are instrumental".
--but actually I wanted to sketch an in-order explanation; let's get to that.
---
Q: What is a monad?
A: Any type T<A> with a single parameter, which has a natural and sensible implementation of flatMap(T<A>, A -> T<B>) -> T<B>, is a monad. A: (Optionally, Monad can be an interface declared within the language that demands a flatMap from its implementations, but even absent that, types T<A> that have an accompanying flatMap deserve to be called monads.) A: ((Also, in fairness there's also the unit(A) -> T<A>, but it's slightly less important. ...and I don't have a reasonably intuitive motivation for it.)) A: Array<A> is a monad. Stream<A> is a monad. Future<A> is a monad. Option<A> is a monad. For a fixed Err, Result<A, Err> is a monad. Many more types are monads also, but: later. A: Values of type T<A> are typically called monadic values.
A: Secondly, monadic code is a code style / pattern in which several functions whose return type is T<_> are applied consecutively to each other's outputs with help of flatMap. So e.g. you can have all your business-logic functions return a Result<_, Err>, with Err encoding all the possible processing errors, and combine them uncomplicatedly: parseOptions().flatMap(loadThingsFromDisk).flatMap(parseThings).flatMap(resolveIDsViaDB).flatMap(performInstructedActions).......
Q: ........uh.....sure.....great? Why would I ever want to do that. Drop the flatMaps and that's a normal OOP processing pipeline, what's the point of all that...cruft. A: Two parts here. One, you can encode all kinds of side effects a function can have as {aptly named single-parameter types that implement flatMap} which appear in the function's return type. Pure functions except they produce some concatenatable side-output like logs: done, the Writer monad; pure functions except they are allowed to alter some delineated state: done, the State monad, pure functions except they're allowed read access to some unchangeable context—you get the idea. A: (Better yet, it's easy to modify most of those into a combinable form, so you can have functions that write a log, and touch a state, and might return an error, all those capabilities represented in the return type, and then compose them with the exact same flatMap.) A: Secondly, I claim that you really really want to encode side effects in return types. A: One good reason is readability. The Result<_, Err> type you learn once and use everywhere; to recognize it in new form again and again every time it's reimplemented is more effort and more errors. Res, Option, State all have standardized methods and contracts; after the tenth time you don't even need to think about their internal logic, it's just...obvious what will happen in a given chunk of code, or how to produce some particular effect you desire. A: And another, possibly more important: as long as side effects are type-encoded, you can delegate tracking them to the compiler. No more unexpected test or production breakages due to unexpected change in side-effects of some distant refactoring! No more unhandled null references! A new effect—or new variety-of-result, like Option or Result—won't compile until and unless you also fix all the consumers/use-locations of the altered function to cope with the new changes somehow.
A: With that in mind, monads are just all those type-encoded effects/capabilities where it's obvious how consecutive applications of the effect / invocations of the capability should be combined; that is, where the combining logic is enshrined in that type's flatMap. Their main use is to work with type-encoded effects comparatively painlessly, letting us have considerable benefits of such encoding without the otherwise-noticeable cost of composing effects manually.
<Q has further critique, but A is out of exposition.>
10 notes · View notes
ssblur · 6 months ago
Note
ifPresent() over flatMap(stream)? using streams in a mixin body??? sorry blur pal i think we actually hafta kill you for this one
(:
2 notes · View notes
newpronounswhodis · 1 year ago
Note
you like haskell?
explain what a monad is!
a monad is a type with a flatmap operation and I’m tired of people overcomplicating it
consider some type M which is generic over T. in rust that is expressed as “struct M<T>”, or in haskell as “data M a = …”. If there is a function with the signature “M a -> (a -> M b) -> M b”, then it is a Monad. Simple as
2 notes · View notes
forever-stuck-on-java-8 · 4 months ago
Text
This is just Java Slander. And skill issue.
First of all, steam() isn't necessary for forEach() you could simplify it to: list.forEach(list2::add)
However this entire thing can be simplified to list2.addAll(list).
If you need the result in a new list, their are multiple ways to do so:
Normal way: List<> newList = new ArrayList<>(list2); newList.addAll(list);
Using Stream: List<> newList = Stream.concat(list.stream(), list2.stream()).collect(Collectors.toList());
Using Stream.of() (which can do more than 2): List<> newList = Stream.of(list, list2, list3) .flatMap(Collection::stream) .collect(Collectors.toList());
Using Apache Commons: List<> newList = ListUtils.union(list1, list2);
i fucking hate writing java dude what do you mean list.stream().forEach(list2::add)??!
syntax written by clowns
393 notes · View notes
souhaillaghchimdev · 13 days ago
Text
Kotlin: 100 Simple Codes
Tumblr media
Kotlin: 100 Simple Codes
beginner-friendly collection of easy-to-understand Kotlin examples.
Tumblr media
Each code snippet is designed to help you learn programming concepts step by step, from basic syntax to simple projects. Perfect for students, self-learners, and anyone who wants to practice Kotlin in a fun and practical way.
Codes:
1. Hello World
2. Variables and Constants
3. If-Else Statement
4. When Statement (Switch)
5. For Loop
6. While Loop
7. Functions
8. Return Value from Function
9. Array Example
10. List Example
===
11. Mutable List
12. Map Example
13. Mutable Map
14. Class Example
15. Constructor with Default Value
16. Nullable Variable
17. Safe Call Operator
18. Elvis Operator
19. Data Class
20. Loop with Index
===
21. Lambda Function
22. Higher-Order Function
23. Filter a List
24. Map a List
25. String Interpolation
26. String Templates with Expressions
27. Read-Only vs Mutable List
28. Check Element in List
29. Exception Handling
30. Null Check with let
===
31. For Loop with Step
32. For Loop in Reverse
33. Break in Loop
34. Continue in Loop
35. Check String Empty or Not
36. Compare Two Numbers
37. Array Access by Index
38. Loop Through Map
39. Default Parameters in Function
40. Named Arguments
===
41. Range Check
42. Function Returning Unit
43. Multiple Return Statements
44. Chained Method Calls
45. Function Inside Function
46. Function Expression Syntax
47. Array Size
48. String to Int Conversion
49. Safe String to Int Conversion
50. Repeat Block
===
51. Sealed Class
52. Object Expression (Anonymous Object)
53. Singleton using Object Keyword
54. Extension Function
55. Enum Class
56. Use Enum in When Statement
57. Type Alias
58. Destructuring Declarations
59. Companion Object
60. Simple Interface Implementation
===
61. Abstract Class
62. Lateinit Variable
63. Initialization Block
64. Secondary Constructor
65. Nested Class
66. Inner Class
67. Generic Function
68. Generic Class
69. Custom Getter
70. Custom Setter
===
71. String Equality
72. Loop with Range Until
73. Using Pair
74. Triple Example
75. Check Type with is
76. Smart Cast
77. Type Casting with as
78. Safe Casting with as?
79. Loop Through Characters of String
80. Sum of List
===
81. Min and Max of List
82. Sort List
83. Reverse List
84. Count Items in List
85. All / Any Conditions
86. Check if List is Empty
87. Join List to String
88. Take and Drop
89. Zipping Lists
90. Unzipping Pairs
===
91. Chunked List
92. Windowed List
93. Flatten List
94. FlatMap
95. Remove Duplicates
96. Group By
97. Associate By
98. Measure Execution Time
99. Repeat with Index
100. Create Range and Convert to List
===
0 notes
bigdataschool-moscow · 1 year ago
Link
0 notes
eccentric-nucleus · 1 year ago
Text
```parseExpr("$foobar + $baz * 2 * %quux").flatMap (expr => evaluateExpr ({local: {quux: 12}, global: {foobar: 5, baz: 10}}, expr))
Object { right: 1, val: 245 }```
well that was easy :toot:
0 notes
javainspires · 1 year ago
Video
youtube
Java 8 FlatMap Example Java Inspires
0 notes
javatute673 · 2 years ago
Text
Java Stream flatMap()
Tumblr media
0 notes
notarealwelder · 1 year ago
Text
A monad is any single-parameter type that has a natural and sensible flatMap, what's the problem
maths student naïvely asks for the definition of a tensor, causes world war 3, more on this story at 7
539 notes · View notes
proeduorganization · 4 years ago
Text
Apache Spark flatMap transformation
Apache Spark flatMap transformation
Apache Spark flatMap transformation Apache Spark In our previous post, we talked about the Map transformation in Spark. In this post we will learn the flatMap transformation. As per Apache Spark documentation, flatMap(func) is similar to map, but each input item can be mapped to 0 or more output items That means the func should return a scala.collection.Seq rather than a single item. Let’s…
Tumblr media
View On WordPress
0 notes
magicalalehouse · 4 years ago
Text
Tumblr media
Made a top view of the proposed scene, with a half buried hedron in the middle nad a broken on the side. squares represents cabins and circle represent trees. Circle with a cross represent more lifeless tree, purhaps burned and snow covered? The sky should also contain some hedrons floating in the distance. Hedrons should be futuristic but with exposed components representing damage perhaps? Or can go for a more steampunk vibe with pistons outside? Cabins need to be primitive and maybe even collapsed cabins. the whole scene need to be covered in snow. Have not yet decided if human figures will be included. Could add some smoke indicating camp fire.
0 notes
hunteroil456 · 4 years ago
Text
Crusader Kings 3 Lord Of The Rings
Tumblr media
Crusader Kings in Middle-earth. Announcing LotR: Realms in Exile for CK3. We have a map, and a team. And are looking for people to share in our adventures.(reddit.com)
Crusader Kings 3 Lord Of The Rings Mods
Crusader Kings 3 Lord Of The Rings Movies
Crusader Kings II is a sequel to the historical Real-Time Strategy game Crusader Kings also by Paradox Interactive.Playing similarly to the first game, with the player controlling the leader of a dynasty rather than acting as an abstract Non-Entity General, this iteration added several more features like character ambitions, an expanded plotting and intrigue mechanic, a revamp of the holy. An expansive medieval grand-strategy game of war, intrigue, and custom character design – of course there’s a Lord of the Rings mod for Crusader Kings 3. The premise is simple enough: take the vanilla game’s core gameplay and plonk it into the realm of Middle-earth, complete with a lovingly-designed map, character portraits of your.
Welcome to another Mod Monday where we cover the Best Ck3 mods of the week or weeks? Sub here: Mondays: Mods. Welcome to Amazon UK’s PC & Video Games Shop. Browse the latest consoles and games; includes PS4, Xbox One, Nintendo Wii U, PC Games & more.
submitted by Barad-Dûr
Crusader Kings in Middle-earth. Announcing LotR: Realms in Exile for CK3. We have a map, and a team. And are looking for people to share in our adventures.
Crusader Kings 3 Lord Of The Rings Mods
Tumblr media Tumblr media
7,509 points•368 comments•submitted by to r/CrusaderKings
Caption: The realms of Middle-earth. This is for the first release, future releases will include Gondor, Mordor, Erebor, Rhovanion, Mirkwood and more.
Crusader Kings 3 Lord Of The Rings Movies
Caption: The hand-drawn flatmap. It's much bigger than this...
Tumblr media
3 notes · View notes
programmerhumour · 6 years ago
Photo
Tumblr media
When you forget to use flatMap
393 notes · View notes
lovecreat12345 · 6 years ago
Text
FlatMap In Angular
FlatMap In Angular
This Article is about FlatMap In Angular. Let’s say we wanted to implement an AJAX search feature in which every keypress in a text field will automatically perform a search and update the page with the results. How would this look? Well we would have an Observablesubscribed to events coming from an input field, and on every change of input we want to perform some HTTP…
View On WordPress
0 notes