FAQ Database Discussion Community


Getting every Friday until a certain date, but in a functional style?

javascript,haskell,functional-programming,underscore.js,lazy-evaluation
For example, I want to get the dates of every Friday from now until 30 days from now. Currently, I can make use of the underscore library and moment.js to do this. But the result is super verbose and annoyingly procedural/imperative. Observe: var initDate = moment().day("Friday"); var endDate = moment().add(30,...

How do I force a function to be called immediately in Haskell?

haskell,lazy-evaluation,memoization
This is my code: import Data.Function.Memoize import Debug.Trace foo :: Int -> Int -> Int foo a = memoFix fooMemo where fooMemo f x = a + (trace (show x) cont) where cont = if x == 0 then 0 else x + f (x - 1) main = do...

Lazy evaluation macro with Sweet.js

javascript,lazy-evaluation,sweet.js
I just got in JavaScript and noticed that lazy evaluation is not directly supported in this language. Natively the code turns into the hell of boiler plate like this: function lazy(f) { var v = undefined; return function() { if (v == undefined) v = f(); return v; } }...

ggplot: aesthetics from variable string without aes_string

r,ggplot2,lazy-evaluation
i have a variable v containing a data.frame column name. I now want to plot it against its index. Normally, plotting a column against its index is easy: df <- data.frame(a = c(.4, .5, .2)) ggplot(df, aes(seq_along(a), a)) + geom_point() But in my case, I can’t figure out what incantations...

ConcurrentDictionary Lazy AddOrUpdate

.net,c#-4.0,lazy-evaluation,concurrentdictionary
I found this Extension for C# to convert GetOrAdd to Lazy and I want to do the same for AddOrUpdate. Can someone help me convert this to AddOrUpdate? public static class ConcurrentDictionaryExtensions { public static TValue LazyGetOrAdd<TKey, TValue>( this ConcurrentDictionary<TKey, Lazy<TValue>> dictionary, TKey key, Func<TKey, TValue> valueFactory) { if (dictionary...

Can Try be lazy or eager in Scala?

scala,lazy-evaluation,lazy-initialization,eager
AFAIK, Iterator.map is lazy while Vector.map is eager, basically because they are different types of monads. I would like to know if there is any chance of having a EagerTry and LazyTry that behave just like the current Try, but with the latter (LazyTry) delaying the execution of the closure...

returning functions in R - when does the binding occur?

r,function,functional-programming,lazy-evaluation
As in other functional languages, returning a function is a common case in R. for example, after training a model you'd like to return a "predictor" object, which is essentially a function, that given new data, returns predictions. There are other cases when this is useful, of course. My question...

How to properly make a lazy derived property on a mutating struct in Swift?

swift,struct,lazy-evaluation,mutable
I'm making a mutating struct with a really expensive-to-compute derived value. So what I want to do is to compute this derived value lazily and store the result, until the struct gets mutated again, at which point the derived value is no longer valid and needs to be recomputed. (Failed)...

Lazy loading using nodejs and mongoDB as backend data

node.js,mongodb,load,lazy-evaluation
Our collection has around 100 million documents. We created a simple application using nodejs and expressjs with a limit clause in the mongo query . It is sufficient for the users as of now. In the mean time we are trying to implement lazy loading so that the initial page...

Haskell: how is readMay evaluated?

haskell,lazy-evaluation
I was looking at a tutorial in School of Haskell, when a particular piece of code puzzled me. The snippet below, in my opinion, should not work, but it does. There is something about the evaluation of readMay in this case that I didn't quite understand. import Safe (readMay) main...

Logical short-circuit inside a function handle

matlab,lazy-evaluation,anonymous-function,logical-operators,short-circuiting
I have a function handle that operates on 2d arrays of arbitrary size: R2T = @(DL1,DL2) arrayfun(@(DL1,DL2)... 1/(fzero(@(x)fFitObj1(x)./fFitObj2(x)-... DL1./DL2,[minLim maxLim])) ... ,DL1,DL2) - C1; Here's a bottom-up breakdown of what it does: fzero(@(x)fFitObj1(x)./fFitObj2(x)-DL1./DL2,[minLim maxLim]) - This bit looks for a zero of the considered function on the interval [minLim maxLim],...

Is there a lazy functional (immutable) language where functions have intermediate variables+return?

scope,functional-programming,lazy-evaluation
I apologize if this has an obvious answer. I would like to find a lazy functional programming language where the following pseudo code makes sense: let f = function(x) { let y = x*x // The variables y and z let z = y*2 // are local return z }...

lazy-seq and stack overflow for infinite sequences [duplicate]

clojure,lazy-evaluation,lazy-sequences
This question already has an answer here: Recursive function causing a stack overflow 1 answer I am trying to show the importance of lazy-sequences or lazy-evaluation to the non-FP programmers. I have written this implementation of prime-generation to show the concept: (defn primes-gen [sieve] (if-not (empty? sieve) (let [prime...

function call within a function in R [duplicate]

r,function,lazy-evaluation
This question already has an answer here: Explain a lazy evaluation quirk 2 answers This is an example from Hadley's latest book (Advanced R). I hope he does not mind that I posted it. I am having difficulty to understand why this code snippet does what it does. Could...

Is there any option to defer the evaluation of a function call in a variadic template

c++,c++11,lazy-evaluation,variadic-templates
Suppose a variadic template: void f(T value, Args... args) As one of the arguments a function is passed which returns a value. Example: f(1, getName()); Is there a simple way to defer the evaluation of the function, so getName() is invoked inside f() and is not executed if not required....

Haskell: if-then-else blocks and data with asymmetrical constructors

haskell,types,functional-programming,lazy-evaluation,purely-functional
I have the following data which can have a Ship or not: data LaserCollisionResult = NoCollision | LaserToLaserCollision Ship | LaserToShipCollision Ship deriving (Eq, Show) then, later on, I am trying to check if a LaserCollisionResult is of type LaserToLaserCollision, but I get an error. My [lambda] function is this:...

Is equality testing possible between two infinite data structure in Haskell?

haskell,lazy-evaluation,infinite
In a project I'm working on, data of a certain type may sometimes contain themselves in it. For example, data Example = Apple Int | Pear Int Example a = Pear 10 a b = Pear 10 b As a programmer I know that a and b are equal, but...

How to stop lazy evaluation slowing down a divide and conquer algorithm

algorithm,recursion,f#,lazy-evaluation
I was using a recursive function in F Sharp to build a particular tree structure, using containers that were evaluated at each stage. I was instructed to use Seq instead because it lazy evaluation should minimize the number of operation. (I understand that, for example, .NET sort functions using lazy...

Guaranteed Detection of Temporary->Named Points

c++,c++11,design,move,lazy-evaluation
Suppose you write a matrix class with some operations: class matrix { public: double operator()(size_t i, size_t j) const; ... }; matrix operator*(const matrix &lhs, const matrix &rhs); ... It makes sense to defer the evaluation of some matrix expressions: m0 * m1 * m2 * m3 * m4 (which...

Lazy evaluation of expression in Elixir

lazy-evaluation,elixir
I'm trying to figure out if there is a macro similar to delay in clojure to get a lazy expression/ variable that can be evaluated later. The use case is a default value for Map.get/3, since the default value comes from a database call, I'd prefer it to be called...

Lazy functions evaluation in swift

ios,swift,if-statement,functional-programming,lazy-evaluation
Wondering is it possible to evaluate a simple if statement lazily. Below is an example that will print "this is foo" and "this is bar", but I really want to make it print only the first string: func foo() { println("this is foo") } func bar() { println("this is bar")...

What's the advantage using lazy evaluation in Queue data structure?

ocaml,lazy-evaluation
I'm reading Purely Functional Data Structures written by Chris Okasaki. In chapter 6, the book introduces lazy evaluation to us, I compared the two version (* https://github.com/mmottl/pure-fun/blob/master/chp5.ml#L47 *) module BatchedQueue : QUEUE = struct type 'a queue = 'a list * 'a list let empty = [], [] let is_empty...

Racket: inner reduction vs. lazy evaluation?

racket,lazy-evaluation,evaluation
I thought racket does inner reduction always for evaluation but I found out e.g. "if" (and cond?!) is lazy evaluation in racket...why is this needed? Is it impossible to realize an if-statement via inner reduction? I can not figure out where lazy evaluation is better than inner and vice versa?...

Mutable vs Lazy Evaluation

c++,const,lazy-evaluation,mutable
Recently I was reading this faq on const-correctness. Now I came across the following situation where I dont know what to make const or mutable. Assume the simple example: class Averager { public: Averager() : sum(0),isUptoDate(false),N(0){} void add(double x){ sum+=x; N+=1; isUptoDate = false; } double getAverage() const { if...

fine tune range`s laziness [duplicate]

clojure,lazy-evaluation
This question already has an answer here: How do I avoid Clojure's chunking behavior for lazy seqs that I want to short circuit? 3 answers This code: (first (map (fn [d] (apply * (repeat d 10))) (range))) yealds an integer overflow exception, while this code: (first (map (fn [d]...

Is it possible to showcase the different strategies of evaluation by modifying this simple reducer?

haskell,lambda,functional-programming,lazy-evaluation,lambda-calculus
I am the kind that prefers learning by looking at code instead of reading long explanations. This might be one of the reasons I dislike long academic papers. Code is unambiguous, compact, noise-free and if you don't get something you can just play with it - no need to ask...

Python lazy evaluation?

python,lazy-evaluation
Suppose I have the following code: def my_func(input_line): is_skip_line = self.is_skip_line(input_line) # parse input line check if skip line if is_skip_line: # do something... # do more ... if is_skip_line: # do one last thing So we have a check for is_skip_line (if is_skip_line:) that appears twice. Does it mean...

Swift Struct with Lazy, private property conforming to Protocol

swift,struct,protocols,lazy-evaluation
First, I have a protocol that defines only a few, readonly properties, ex: protocol Example { var var1:String { get } var varArray:[String] { get } } I then want to create a struct that conforms to that protocol. The problem I'm running into, is that I have two conflicting...

Haskell return lazy string from file IO

haskell,file-io,lazy-evaluation
Here I'm back again with a (for me) really strange behaviour of my newest masterpiece... This code should read a file, but it doesn't: readCsvContents :: String -> IO ( String ) readCsvContents fileName = do withFile fileName ReadMode (\handle -> do contents <- hGetContents handle return contents ) main...

In lodash.js, will it cache the result for `.value()` method?

javascript,coffeescript,underscore.js,lazy-evaluation,lodash
For example, I have codes (coffeescript) like this: sortedLatLng = _(w) .sortBy (x) -> x.time .map (x) -> [x.longitude,x.latitude] .uniq((x)-> x[0].toFixed(3) + "," + x[1].toFixed(3)) # keep three decimal to merge nearby points console.log(sortedLatLng.value()) myFunction1(sortedLatLng.value()) myFunction2(sortedLatLng.value()) console.log(sortedLatLng.reverse().value()) This may be chained by other lodash method later. Meanwhile, its value may...

Why is lazy evaluation in Haskell “not being lazy”?

haskell,lazy-evaluation
When I tried the following code in cghi: take 1 $ take 1 $ repeat [1..] I was expecting the result of 1 instead of [[1,2,3,4,5,6,7,8,9,10,... printing on my terminal. Why is lazy evaluation not functioning as I'm hoping under such situation?...

In python, can I lazily generate copies of an iterator using tee?

python,iterator,lazy-evaluation
I'm trying to create an iterator which lazily creates (potentially infinitely many) copies of an iterator. Is this possible? I know I can create any fixed finite number of copies by simply doing iter_copies = tee(my_iter, n=10) but this breaks down if you don't know n ahead of time or...

Is this possible to implement laziness with circular dependencies in Scala?

scala,lazy-evaluation
This code causes Stackoverflow error: lazy val leftChild = new Node(true, root, Seq(2), Seq()) lazy val rightChild = new Node(true, root, Seq(3), Seq()) lazy val root :Node = new Node(false, null, Seq(1), Seq(leftChild, rightChild)) where Node is defined as follows: case class Node(isLeaf: Boolean, parent: Node, keys: Seq[Int], pointers: Seq[Node])...

Computing a term of a list depending on all previous terms

haskell,recursion,functional-programming,lazy-evaluation,formal-methods
I have the following identity, that defines (implicitly) the number of partitions of positive integers (that is, the number of ways you can write the integer as the sum of ordered positive nonzero integers): Some notes: This is studied in the book Analytic Combinatorics by Flajolet and Sedjewick, and the...

What is the exact difference in behavior between `++` and `#:::` when you concatenate two streams?

scala,lazy-evaluation
To be more specific, I had a code similar to the following one (some of you will probably recognize the pattern of the last assignment of the coursera Functional Programming Course), that failed to find the solution with ++ but worked with #::: (the set of alreadySeen solution contained a...

lazyeval in ggplot2 within other function

r,ggplot2,lazy-evaluation
I have a problem and I could not find the answer in this solution. I mean, I want to use the ggplot function within a new function, e.g. library(ggplot2) draw_point <- function(data, x, y ){ ggplot(data, aes_string(x, y)) + geom_point() } and in result I have to use quotation marks:...

How in Grails override config variable in external config file so that variables dependant on that variable are updated too?

grails,groovy,config,lazy-evaluation
I have an external and internal config in my grails application: Config.groovy root = "/home/baseConf" test { dir = root + "/testDir" } External.groovy root = "/home/externalConf" Inside controller i have: println "${grailsApplication.config.root}" println "${grailsApplication.config.test.dir}" What is printed: /home/externalConf /home/baseConf/testDir What I want to be printed: /home/externalConf /home/externalConf/testDir What should...

in haskell, how to represent infinite data which is newly defined

haskell,types,lazy-evaluation
I defined a new data type in Haskell in the following way: data Pro = P Int Pro | Idle deriving Show Then I defined a operator which works for this new data type: (>*>) :: Pro -> Pro -> Pro Idle >*> ps = ps P i ps >*>...

Lazy Val - How to reset value?

scala,lazy-evaluation
I may want to use a method that is expensive and returns a result depending on side effects. For example depending on the time of day / week and a Monte Carlo simulation of quantum chronodynamics. Because it's expensive and I may not need it, I'll use Scalas lazy val...