If I have two lists
val first = List(1, 2, 3)
val second = List(4, 5, 6)
How would I obtain the following?
(1-4)^2 + (2-5)^2 + (3-6)^2
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
zip, map and sum:
(edit to replace
reduceLeftbysum)After seeing the comments, I feel I had to come back and explain about views. Basically a view turns a
Traversableinto an iterator like structure so that multiple intermediate structures don’t have to be created when apply methods likemap,zipand a few others. The type members of GenIteratableViewLike gives a sense of what operations have special processing. So typically if you have a bunch of map, filter, drop, takeWhile applied in sequence, you can use view to gain some performance. The rule of thumb is to applyviewearly to minimize how many intermediateListare created and if necessary useforceat the end to go back toList(or whatever collection you’re using). Thus Daniel’s suggestion.The thing about performance is that in practice if that’s important you sort of have to do a reality check. Here are some numbers (lower is better):
Code is here: