How can I use the last result from a scala map as input to the next function? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live!Ways to improve this codeHow does this permutations function work (Scala)?How can a time function exist in functional programming?Group By (Aggregate Map Reduce Functions) in MongoDB using Scala (Casbah/Rogue)Terminal function for collections in scalahow to write hadoop map reduce programs in scalaWhy does Spark fail with java.lang.OutOfMemoryError: GC overhead limit exceeded?Create array of literals and columns from List of Strings in Spark SQLScala apply function on list elements to return a valueScala for comprehension how to avoid creating of Future when passing results
What are the main differences between the original Stargate SG-1 and the Final Cut edition?
Simple HTTP Server
Did any compiler fully use 80-bit floating point?
Sally's older brother
Can you force honesty by using the Speak with Dead and Zone of Truth spells together?
Tannaka duality for semisimple groups
As a dual citizen, my US passport will expire one day after traveling to the US. Will this work?
What is the difference between a "ranged attack" and a "ranged weapon attack"?
Found this skink in my tomato plant bucket. Is he trapped? Or could he leave if he wanted?
Does the Black Tentacles spell do damage twice at the start of turn to an already restrained creature?
Was Kant an Intuitionist about mathematical objects?
Why not use the yoke to control yaw, as well as pitch and roll?
My mentor says to set image to Fine instead of RAW — how is this different from JPG?
Nose gear failure in single prop aircraft: belly landing or nose-gear up landing?
Asymptotics question
What is a more techy Technical Writer job title that isn't cutesy or confusing?
Resize vertical bars (absolute-value symbols)
How to align enumerate environment inside description environment
Moving a wrapfig vertically to encroach partially on a subsection title
Random body shuffle every night—can we still function?
Why do early math courses focus on the cross sections of a cone and not on other 3D objects?
How does light 'choose' between wave and particle behaviour?
After Sam didn't return home in the end, were he and Al still friends?
Is openssl rand command cryptographically secure?
How can I use the last result from a scala map as input to the next function?
Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!Ways to improve this codeHow does this permutations function work (Scala)?How can a time function exist in functional programming?Group By (Aggregate Map Reduce Functions) in MongoDB using Scala (Casbah/Rogue)Terminal function for collections in scalahow to write hadoop map reduce programs in scalaWhy does Spark fail with java.lang.OutOfMemoryError: GC overhead limit exceeded?Create array of literals and columns from List of Strings in Spark SQLScala apply function on list elements to return a valueScala for comprehension how to avoid creating of Future when passing results
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;
I'm working through some project euler questions to practice my scala. For problem 7 I have to find the 10001st prime. I have a working solution, but dont feel its as functional as it could be.
def first_n_primes(n: Long) : List[Long] =
var last_prime = 1L
(1L to n).map(x => last_prime = get_next_prime(x, last_prime); last_prime).toList
Specifically, I feel there might be a way to get rid of the var last_prime, but I dont know how to use the result of the nth map evaluation as the input to the n+1 evaluation. How can I do this more functionally?
scala
add a comment |
I'm working through some project euler questions to practice my scala. For problem 7 I have to find the 10001st prime. I have a working solution, but dont feel its as functional as it could be.
def first_n_primes(n: Long) : List[Long] =
var last_prime = 1L
(1L to n).map(x => last_prime = get_next_prime(x, last_prime); last_prime).toList
Specifically, I feel there might be a way to get rid of the var last_prime, but I dont know how to use the result of the nth map evaluation as the input to the n+1 evaluation. How can I do this more functionally?
scala
What is your question exactly ? Is there a way to use result of map or how to solve the problem 7?
– Shantiswarup Tunga
Mar 22 at 12:26
I've solved problem 7. get_next prime starts from the last prime so its not rediscovering old primes - I just want to know if theres a better way to get the result from the nth evalauation to be an input to the n+1 evaluation.
– Andrew Bucknell
Mar 22 at 23:08
You can usescan,scanLeft,fold,foldLeft,reduce, reduceLeft
higher order function for getting the result from nth evaluation
– Shantiswarup Tunga
Mar 23 at 4:13
add a comment |
I'm working through some project euler questions to practice my scala. For problem 7 I have to find the 10001st prime. I have a working solution, but dont feel its as functional as it could be.
def first_n_primes(n: Long) : List[Long] =
var last_prime = 1L
(1L to n).map(x => last_prime = get_next_prime(x, last_prime); last_prime).toList
Specifically, I feel there might be a way to get rid of the var last_prime, but I dont know how to use the result of the nth map evaluation as the input to the n+1 evaluation. How can I do this more functionally?
scala
I'm working through some project euler questions to practice my scala. For problem 7 I have to find the 10001st prime. I have a working solution, but dont feel its as functional as it could be.
def first_n_primes(n: Long) : List[Long] =
var last_prime = 1L
(1L to n).map(x => last_prime = get_next_prime(x, last_prime); last_prime).toList
Specifically, I feel there might be a way to get rid of the var last_prime, but I dont know how to use the result of the nth map evaluation as the input to the n+1 evaluation. How can I do this more functionally?
scala
scala
asked Mar 22 at 11:47
Andrew BucknellAndrew Bucknell
7683927
7683927
What is your question exactly ? Is there a way to use result of map or how to solve the problem 7?
– Shantiswarup Tunga
Mar 22 at 12:26
I've solved problem 7. get_next prime starts from the last prime so its not rediscovering old primes - I just want to know if theres a better way to get the result from the nth evalauation to be an input to the n+1 evaluation.
– Andrew Bucknell
Mar 22 at 23:08
You can usescan,scanLeft,fold,foldLeft,reduce, reduceLeft
higher order function for getting the result from nth evaluation
– Shantiswarup Tunga
Mar 23 at 4:13
add a comment |
What is your question exactly ? Is there a way to use result of map or how to solve the problem 7?
– Shantiswarup Tunga
Mar 22 at 12:26
I've solved problem 7. get_next prime starts from the last prime so its not rediscovering old primes - I just want to know if theres a better way to get the result from the nth evalauation to be an input to the n+1 evaluation.
– Andrew Bucknell
Mar 22 at 23:08
You can usescan,scanLeft,fold,foldLeft,reduce, reduceLeft
higher order function for getting the result from nth evaluation
– Shantiswarup Tunga
Mar 23 at 4:13
What is your question exactly ? Is there a way to use result of map or how to solve the problem 7?
– Shantiswarup Tunga
Mar 22 at 12:26
What is your question exactly ? Is there a way to use result of map or how to solve the problem 7?
– Shantiswarup Tunga
Mar 22 at 12:26
I've solved problem 7. get_next prime starts from the last prime so its not rediscovering old primes - I just want to know if theres a better way to get the result from the nth evalauation to be an input to the n+1 evaluation.
– Andrew Bucknell
Mar 22 at 23:08
I've solved problem 7. get_next prime starts from the last prime so its not rediscovering old primes - I just want to know if theres a better way to get the result from the nth evalauation to be an input to the n+1 evaluation.
– Andrew Bucknell
Mar 22 at 23:08
You can use
scan,scanLeft,fold,foldLeft,reduce, reduceLeft
higher order function for getting the result from nth evaluation– Shantiswarup Tunga
Mar 23 at 4:13
You can use
scan,scanLeft,fold,foldLeft,reduce, reduceLeft
higher order function for getting the result from nth evaluation– Shantiswarup Tunga
Mar 23 at 4:13
add a comment |
1 Answer
1
active
oldest
votes
You are looking for scanLeft
:
(1l to n).scanLeft(1) case (x, last) => get_next_prime(x, last)
Or just (1l to n).scanLeft(1)(get_next_prime)
Note however that this is not a very good algorithm looking for the primes, because there is a lot of repetitive work that could be saved (to find the next prime, you need to re-discover all the previous ones).
This sort of task is better done in scala with recursive streams:
lazy val primes: Stream[Long] = 2 #:: Stream.iterate(3l)(_+1).filter n =>
val stop = math.sqrt(n)
primes.takeWhile _ <= stop .forall k => n % k != 0
primes.take(n).toList
scanLeft is perfect! Thankyou! The one change I made is last is actually the first parameter as it holds the result of the previous operation. So I changed the signature of get_next_prime to reflect this. The use of scanleft lets me avoid recalculating previous primes because now I always start from the last prime calculated.
– Andrew Bucknell
Mar 22 at 23:36
It's not just where you start that matters. When you check whether a given number is prime, you don't have to try to divide it by every smaller number, it is enough to verify only primes.
– Dima
Mar 23 at 12:24
add a comment |
Your Answer
StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");
StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);
else
createEditor();
);
function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55298939%2fhow-can-i-use-the-last-result-from-a-scala-map-as-input-to-the-next-function%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
You are looking for scanLeft
:
(1l to n).scanLeft(1) case (x, last) => get_next_prime(x, last)
Or just (1l to n).scanLeft(1)(get_next_prime)
Note however that this is not a very good algorithm looking for the primes, because there is a lot of repetitive work that could be saved (to find the next prime, you need to re-discover all the previous ones).
This sort of task is better done in scala with recursive streams:
lazy val primes: Stream[Long] = 2 #:: Stream.iterate(3l)(_+1).filter n =>
val stop = math.sqrt(n)
primes.takeWhile _ <= stop .forall k => n % k != 0
primes.take(n).toList
scanLeft is perfect! Thankyou! The one change I made is last is actually the first parameter as it holds the result of the previous operation. So I changed the signature of get_next_prime to reflect this. The use of scanleft lets me avoid recalculating previous primes because now I always start from the last prime calculated.
– Andrew Bucknell
Mar 22 at 23:36
It's not just where you start that matters. When you check whether a given number is prime, you don't have to try to divide it by every smaller number, it is enough to verify only primes.
– Dima
Mar 23 at 12:24
add a comment |
You are looking for scanLeft
:
(1l to n).scanLeft(1) case (x, last) => get_next_prime(x, last)
Or just (1l to n).scanLeft(1)(get_next_prime)
Note however that this is not a very good algorithm looking for the primes, because there is a lot of repetitive work that could be saved (to find the next prime, you need to re-discover all the previous ones).
This sort of task is better done in scala with recursive streams:
lazy val primes: Stream[Long] = 2 #:: Stream.iterate(3l)(_+1).filter n =>
val stop = math.sqrt(n)
primes.takeWhile _ <= stop .forall k => n % k != 0
primes.take(n).toList
scanLeft is perfect! Thankyou! The one change I made is last is actually the first parameter as it holds the result of the previous operation. So I changed the signature of get_next_prime to reflect this. The use of scanleft lets me avoid recalculating previous primes because now I always start from the last prime calculated.
– Andrew Bucknell
Mar 22 at 23:36
It's not just where you start that matters. When you check whether a given number is prime, you don't have to try to divide it by every smaller number, it is enough to verify only primes.
– Dima
Mar 23 at 12:24
add a comment |
You are looking for scanLeft
:
(1l to n).scanLeft(1) case (x, last) => get_next_prime(x, last)
Or just (1l to n).scanLeft(1)(get_next_prime)
Note however that this is not a very good algorithm looking for the primes, because there is a lot of repetitive work that could be saved (to find the next prime, you need to re-discover all the previous ones).
This sort of task is better done in scala with recursive streams:
lazy val primes: Stream[Long] = 2 #:: Stream.iterate(3l)(_+1).filter n =>
val stop = math.sqrt(n)
primes.takeWhile _ <= stop .forall k => n % k != 0
primes.take(n).toList
You are looking for scanLeft
:
(1l to n).scanLeft(1) case (x, last) => get_next_prime(x, last)
Or just (1l to n).scanLeft(1)(get_next_prime)
Note however that this is not a very good algorithm looking for the primes, because there is a lot of repetitive work that could be saved (to find the next prime, you need to re-discover all the previous ones).
This sort of task is better done in scala with recursive streams:
lazy val primes: Stream[Long] = 2 #:: Stream.iterate(3l)(_+1).filter n =>
val stop = math.sqrt(n)
primes.takeWhile _ <= stop .forall k => n % k != 0
primes.take(n).toList
edited Mar 23 at 12:48
answered Mar 22 at 11:55
DimaDima
26.7k32640
26.7k32640
scanLeft is perfect! Thankyou! The one change I made is last is actually the first parameter as it holds the result of the previous operation. So I changed the signature of get_next_prime to reflect this. The use of scanleft lets me avoid recalculating previous primes because now I always start from the last prime calculated.
– Andrew Bucknell
Mar 22 at 23:36
It's not just where you start that matters. When you check whether a given number is prime, you don't have to try to divide it by every smaller number, it is enough to verify only primes.
– Dima
Mar 23 at 12:24
add a comment |
scanLeft is perfect! Thankyou! The one change I made is last is actually the first parameter as it holds the result of the previous operation. So I changed the signature of get_next_prime to reflect this. The use of scanleft lets me avoid recalculating previous primes because now I always start from the last prime calculated.
– Andrew Bucknell
Mar 22 at 23:36
It's not just where you start that matters. When you check whether a given number is prime, you don't have to try to divide it by every smaller number, it is enough to verify only primes.
– Dima
Mar 23 at 12:24
scanLeft is perfect! Thankyou! The one change I made is last is actually the first parameter as it holds the result of the previous operation. So I changed the signature of get_next_prime to reflect this. The use of scanleft lets me avoid recalculating previous primes because now I always start from the last prime calculated.
– Andrew Bucknell
Mar 22 at 23:36
scanLeft is perfect! Thankyou! The one change I made is last is actually the first parameter as it holds the result of the previous operation. So I changed the signature of get_next_prime to reflect this. The use of scanleft lets me avoid recalculating previous primes because now I always start from the last prime calculated.
– Andrew Bucknell
Mar 22 at 23:36
It's not just where you start that matters. When you check whether a given number is prime, you don't have to try to divide it by every smaller number, it is enough to verify only primes.
– Dima
Mar 23 at 12:24
It's not just where you start that matters. When you check whether a given number is prime, you don't have to try to divide it by every smaller number, it is enough to verify only primes.
– Dima
Mar 23 at 12:24
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55298939%2fhow-can-i-use-the-last-result-from-a-scala-map-as-input-to-the-next-function%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
What is your question exactly ? Is there a way to use result of map or how to solve the problem 7?
– Shantiswarup Tunga
Mar 22 at 12:26
I've solved problem 7. get_next prime starts from the last prime so its not rediscovering old primes - I just want to know if theres a better way to get the result from the nth evalauation to be an input to the n+1 evaluation.
– Andrew Bucknell
Mar 22 at 23:08
You can use
scan,scanLeft,fold,foldLeft,reduce, reduceLeft
higher order function for getting the result from nth evaluation– Shantiswarup Tunga
Mar 23 at 4:13