Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
Came across this in a discussion on MONADs although a bit hard to follow. But the question is, I can get map and flatmap with Big Data, but the stuff here makes me feel very shaky. firstname => lastname, compounded =>, etc. Not getting it ... Who can explain? It works though.
val maybeFirstName = Option("Joe");
val maybeLastName = Option("Black");
val maybeFullName = maybeFirstName.flatMap { firstName =>
maybeLastName.map { lastName =>
firstName + " " + lastName
}
}
As with many compound operations, it sometimes makes sense to decipher it from the inside out.
maybeLastName.map(lastName => /*some op on lastName*/)
map() opens the Option and assigns the value, if it's there, to lastName. If the Option is None then there is no lastName and no operation on it. If the Option is not None then operation is performed and the result is re-wrapped into an Option.
flatMap() does the same thing except that it doesn't re-wrap the result. Instead the op inside is required to return a value already wrapped, i.e. an Option.
So, to review:
maybeFirstName.flatMap { firstName => //op on firstName must return Option
maybeLastName.map { lastName => //op on lastName should not return Option
/* op */
}
}
If either maybe...Name is None then the final result is None.
Map applies function on maybeLastName and retur Option or Option(Joe Black). So if you use map instead of flatMap, you get Option(Option(Joe Black)), because map always return new Option, so to remove inner option you need to use flatMap or combination map and flatten.
Here you can see how works flatten
Related
This question already has answers here:
How to get a property by this name in String?
(2 answers)
Closed 4 months ago.
I have a typical class userData.
class userData ({K1:V1,K2:V2,K3:V3})
But i want to retrieve the data from several of them at the same time.
userData1 {K1:V1,K2:V2,K3:V3}
userData2 {K1:V4,K2:V5,K3:V6}
userData3 {K1:V7,K2:V7,K3:V8}
instead of using typical direct way:
print ("${userData1.K1} ${userData2.K1} ${userData3.K1}") ;
I want to access the data in an indirect method by using the key name as a String. Something like this:
String MyKey = 'K1';
print ("${userData1[MyKey]} ${userData2[MyKey]} ${userData3[MyKey]}") ;
Is there a way to retireve the values by using the key name as a String?
Thanks in advance for your help
Your question is unclear.
You may be looking for __getitem__. https://docs.python.org/3/library/operator.html#operator.getitem
Consider
d = dict(a=1, b=2)
When you ask for d['a'], you are calling d.__getitem__('a') behind the scenes.
There is an opportunity for your container class to inherit from dict,
and override __getitem__, if you wish to add behavior like logging,
or something fancier.
This is similar to the str() protocol that you likely are already familiar with.
Overriding __str__ will change the behavior of str(...)
and things that call it, such as format(...).
You should certainly review the getattr documentation.
When you write some code that addresses the need to your liking,
do post it here. https://stackoverflow.com/help/self-answer
Here is one solution that worked for me by creating a new dynamic in my class:
class MyClass{
....
dynamic getProp(String key) => <String, dynamic>{
'K1': K1,
'K2': K2,
'K3': K3,
}[key].toString();
}
}
With this i can retrieve with this line:
print(MyClass.getProp("K1"));
And so to get the data from my array, it work like this:
userData1 {K1:V1,K2:V2,K3:V3}
userData2 {K1:V4,K2:V5,K3:V6}
userData3 {K1:V7,K2:V7,K3:V8}
myKey = "K1";
print ("${userData1.getProp("K1")} ${userData2.getProp("K1")} ${userData3.getProp("K1")}"); // prints "V1 V4 V7"
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
How to get an object reference in Scala? I would like to compare those references to see if it's a new or old object which is being used.
var objArr: ArrayBuffer[someObj] = new ArrayBuffer[someObj](0)
// fill array
objArr(0) // how to get the internal reference of that array object and not the content of it?
Any help is highly appreciated!
Actually objArr(0) seems to be what you want
class MyClass
val x = new MyClass
var objArr: ArrayBuffer[MyClass] = ArrayBuffer(x)
objArr(0) eq x // true
objArr(0) eq new MyClass // false
I have an array of words, some may or may not have typos.
potentialWords = ["hello", "lkasjdf", "hunry"]
What I want to do is, return an array of all valid words, and also those words that were able to be autocorrected using a function I created correctWord. It returns an array of potential matches. so "hunry" might return ["hungry", "hurry"]. I will select the first index for the best guess.
Some words cannot be corrected however! e.g. "lkasjdf" will not find any corrections, but "hunry" will.
I was trying something like:
potentialWords.map {
if correctWord($0) != nil {
return correctWord($0)[0]
}
}
of course this will complain and say that I need a return outside the if clause. I can filter the list based on if the word can be corrected, and then map over the filtered list, re-checking which words need to be corrected, but this runs the correctWord function way too many times, and it is very sensitive.
I would like to be able to do one single pass through, and return an array of all valid words, and also corrected words.
P.S. I am calling correctWord twice in the map function for brevity, but of course I would assign correctWord($0) to a variable, and then if it isn't nil, take the first index and add it to the new list.
I think you're after flatMap. It's the same as map except it will also filter out any nil values.
potentialWords.flatMap { correctWord($0)?.first }
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I want to write an if statement that tests two conditions in Groovy, but the language does not appear to support && or &. I'd like to avoid using a nested if statement if possible for this. How can I accomplish this?
Yes groove support the logical-and operator('&&') and bitwise-and operator('&').
class Example {
static void main(String[] args) {
// Initializing a local variable
int a = 2
//Check for the boolean condition
if (a<100 && a>0) {
//If the condition is true print the following statement
println("The value is less than 100");
} else {
//If the condition is false print the following statement
println("The value is greater than 100");
}
}
}
but it is not supporting '&&' or '&'
That's incorrect. Both the logical AND (&&) and the bitwise and (&) work in groovy. See the list of operators in the official documentation.
I don't understand how to describe #helper.repeat in play2.2.1.
#helper.form(action = routes.Application.send) {
#helper.repeat(
field = form1("input"), min = 3
) {fld =>
#helper.inputText(
field = fld, '_label ->"input"
)
}
}
It is the part fld => #helper.inputText(field = fld) that I can't understand.
What does it mean?
I know Java, so I assume it is a functional writing, but in above code, where does the variable fld come from?
And why the tip of the arrow indicates #helper.inputText(field = fld)?
why is fld the value of field in #helper.inputText?
I have googled, but I couldn't find an enough explanation for a beginner.
I am not sure of Scala's grammar.
Please explain above code for a beginner?
Original Answer
This seems to be a bit overcomplicated. There is no need to assign values by hand. Usually you would write a repeater like this:
#helper.repeat(form1("input"), min = 3) { fld =>
#helper.inputText(fld, '_label ->"input")
}
In functional programming this is a so called higher-order function. You may know other scala built in higher-order functions like map, filter or foreach. #helper.repeat is very similar to foreach. form1("input") refers to a collection of values you want to display. min = 1 tells the repeater to show at least one field. Finally within { fld => ... } you iterate over all values defined in your collection.
In other words: { fld => ... } is just an anonymous function that takes a single Field parameter (fld) and displays a text input for that specific field.
Follow Up
Ok, I'm trying to follow up your questions from the comments. Let's start by the signature of helper.repeat. There is no magic involved here, it's just a regular Scala function:
helper.repeat(field: Field, min: Int)(fieldRenderer: (fld: Field) => Html): Seq[Html]
In Scala, functions can have multiple parameter lists. Here we have two. The first parameter list takes two parameters: field and min. The second parameter list takes a single function as parameter: fieldRenderer. fieldRenderer itself takes again a single parameter (fld) and returns Html.
The important thing is, you are not passing "data" but a function instead. To clear this up:
The signature fieldRenderer: (fld: Field) => Html
is equal to def fieldRenderer(fld: Field): Html
This means, you can do anything within this function, as long as it returns Html. That's exactly what happens in the example at the very top. You pass a Field and return Html. You do that by calling #helper.inputText.
Now repeat first gets a List[Field] from field you pass as first parameter. This list corresponds to the String List of your container class. Also repeat ensures there is at least one element in that list. This is, because you passed 1 as min. Then the function fieldRenderer is applied to all elements in our list.
A pseudo code implementation of repeat could look like this:
def repeat(field: Field, min: Int)(fieldRenderer: (fld: Field) => Html): Seq[Html] {
val list: List[Field] = field.getFields
var output: List[Html] = List()
for (i = 0; i < list.length; i++) {
val element: Field = list.get(i)
val html: Html = fieldRenderer(element)
output += html
}
return output
}