Search Results

Search found 727 results on 30 pages for 'evaluation'.

Page 7/30 | < Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >

  • How does 'lazy' work?

    - by Matt Fenwick
    What is the difference between these two functions? I see that lazy is intended to be lazy, but I don't understand how that is accomplished. -- | Identity function. id :: a -> a id x = x -- | The call '(lazy e)' means the same as 'e', but 'lazy' has a -- magical strictness property: it is lazy in its first argument, -- even though its semantics is strict. lazy :: a -> a lazy x = x -- Implementation note: its strictness and unfolding are over-ridden -- by the definition in MkId.lhs; in both cases to nothing at all. -- That way, 'lazy' does not get inlined, and the strictness analyser -- sees it as lazy. Then the worker/wrapper phase inlines it. -- Result: happiness Tracking down the note in MkId.lhs (hopefully this is the right note and version, sorry if it's not): Note [lazyId magic] ~~~~~~~~~~~~~~~~~~~ lazy :: forall a?. a? -> a? (i.e. works for unboxed types too) Used to lazify pseq: pseq a b = a `seq` lazy b Also, no strictness: by being a built-in Id, all the info about lazyId comes from here, not from GHC.Base.hi. This is important, because the strictness analyser will spot it as strict! Also no unfolding in lazyId: it gets "inlined" by a HACK in CorePrep. It's very important to do this inlining after unfoldings are exposed in the interface file. Otherwise, the unfolding for (say) pseq in the interface file will not mention 'lazy', so if we inline 'pseq' we'll totally miss the very thing that 'lazy' was there for in the first place. See Trac #3259 for a real world example. lazyId is defined in GHC.Base, so we don't have to inline it. If it appears un-applied, we'll end up just calling it. I don't understand that because it refers to lazyId instead of lazy. How does lazy work?

    Read the article

  • Rebuilding lazily-built attribute when an underlying attribute changes in Moose

    - by friedo
    I've got a Moose class with a lazy_build attribute. The value of that attribute is a function of another (non-lazy) attribute. Suppose somebody instantiates the class with a value of 42 for the required attribute. Then they request the lazy attribute, which is calculated as a function of 42. Then, they have the nerve to change the first attribute! The lazy one has already been built, so the builder will not get called again, and the lazy attribute is now out-of-date. I have a solution now where I maintain a "dirty" flag on the required attribute, and an accessor on the lazy one checks the dirty flag and rebuilds it if needed. However, this seems like a lot of work. Is there a way to handle this within Moose, e.g. using traits?

    Read the article

  • How to create static method that evaluates local static variable once?

    - by Viet
    I have a class with static method which has a local static variable. I want that variable to be computed/evaluated once (the 1st time I call the function) and for any subsequent invocation, it is not evaluated anymore. How to do that? Here's my class: template< typename T1 = int, unsigned N1 = 1, typename T2 = int, unsigned N2 = 0, typename T3 = int, unsigned N3 = 0, typename T4 = int, unsigned N4 = 0, typename T5 = int, unsigned N5 = 0, typename T6 = int, unsigned N6 = 0, typename T7 = int, unsigned N7 = 0, typename T8 = int, unsigned N8 = 0, typename T9 = int, unsigned N9 = 0, typename T10 = int, unsigned N10 = 0, typename T11 = int, unsigned N11 = 0, typename T12 = int, unsigned N12 = 0, typename T13 = int, unsigned N13 = 0, typename T14 = int, unsigned N14 = 0, typename T15 = int, unsigned N15 = 0, typename T16 = int, unsigned N16 = 0> struct GroupAlloc { static const uint32_t sizeClass; static uint32_t getSize() { static uint32_t totalSize = 0; totalSize += sizeof(T1)*N1; totalSize += sizeof(T2)*N2; totalSize += sizeof(T3)*N3; totalSize += sizeof(T4)*N4; totalSize += sizeof(T5)*N5; totalSize += sizeof(T6)*N6; totalSize += sizeof(T7)*N7; totalSize += sizeof(T8)*N8; totalSize += sizeof(T9)*N9; totalSize += sizeof(T10)*N10; totalSize += sizeof(T11)*N11; totalSize += sizeof(T12)*N12; totalSize += sizeof(T13)*N13; totalSize += sizeof(T14)*N14; totalSize += sizeof(T15)*N15; totalSize += sizeof(T16)*N16; totalSize = 8*((totalSize + 7)/8); return totalSize; } };

    Read the article

  • Iterator blocks in Clojure?

    - by Checkers
    I am using clojure.contrib.sql to fetch some records from an SQLite database. (defn read-all-foo [] (with-connection *db* (with-query-results res ["select * from foo"] (into [] res)))) Now, I don't really want to realize the whole sequence before returning from the function (i.e. I want to keep it lazy), but if I return res directly or wrap it some kind of lazy wrapper (for example I want to make a certain map transformation on result sequence), SQL-related bindings will be reset and connection will be closed after I return, so realizing the sequence will throw an exception. How can I enclose the whole function in a closure and return a kind of iterator block (like yield in C# or Python)? Or is there another way to return a lazy sequence from this function?

    Read the article

  • SQLiteException and SQLite error near "(": syntax error with Subsonic ActiveRecord

    - by nvuono
    I ran into an interesting error with the following LiNQ query using LiNQPad and when using Subsonic 3.0.x w/ActiveRecord within my project and wanted to share the error and resolution for anyone else who runs into it. The linq statement below is meant to group entries in the tblSystemsValues collection into their appropriate system and then extract the system with the highest ID. from ksf in KeySafetyFunction where ksf.Unit == 2 && ksf.Condition_ID == 1 join sys in tblSystems on ksf.ID equals sys.KeySafetyFunction join xval in (from t in tblSystemsValues group t by t.tblSystems_ID into groupedT select new { sysId = groupedT.Key, MaxID = groupedT.Max(g=>g.ID), MaxText = groupedT.First(gt2 => gt2.ID == groupedT.Max(g=>g.ID)).TextValue, MaxChecked = groupedT.First(gt2 => gt2.ID == groupedT.Max(g=>g.ID)).Checked }) on sys.ID equals xval.sysId select new {KSFDesc=ksf.Description, sys.Description, xval.MaxText, xval.MaxChecked} On its own, the subquery for grouping into groupedT works perfectly and the query to match up KeySafetyFunctions with their System in tblSystems also works perfectly on its own. However, when trying to run the completed query in linqpad or within my project I kept running into a SQLiteException SQLite Error Near "(" First I tried splitting the queries up within my project because I knew that I could just run a foreach loop over the results if necessary. However, I continued to receive the same exception! I eventually separated the query into three separate parts before I realized that it was the lazy execution of the queries that was killing me. It then became clear that adding the .ToList() specifier after the myProtectedSystem query below was the key to avoiding the lazy execution after combining and optimizing the query and being able to get my results despite the problems I encountered with the SQLite driver. // determine the max Text/Checked values for each system in tblSystemsValue var myProtectedValue = from t in tblSystemsValue.All() group t by t.tblSystems_ID into groupedT select new { sysId = groupedT.Key, MaxID = groupedT.Max(g => g.ID), MaxText = groupedT.First(gt2 => gt2.ID ==groupedT.Max(g => g.ID)).TextValue, MaxChecked = groupedT.First(gt2 => gt2.ID ==groupedT.Max(g => g.ID)).Checked}; // get the system description information and filter by Unit/Condition ID var myProtectedSystem = (from ksf in KeySafetyFunction.All() where ksf.Unit == 2 && ksf.Condition_ID == 1 join sys in tblSystem.All() on ksf.ID equals sys.KeySafetyFunction select new {KSFDesc = ksf.Description, sys.Description, sys.ID}).ToList(); // finally join everything together AFTER forcing execution with .ToList() var joined = from protectedSys in myProtectedSystem join protectedVal in myProtectedValue on protectedSys.ID equals protectedVal.sysId select new {protectedSys.KSFDesc, protectedSys.Description, protectedVal.MaxChecked, protectedVal.MaxText}; // print the gratifying debug results foreach(var protectedItem in joined) { System.Diagnostics.Debug.WriteLine(protectedItem.Description + ", " + protectedItem.KSFDesc + ", " + protectedItem.MaxText + ", " + protectedItem.MaxChecked); }

    Read the article

  • Does isEmpty method in Stream evaluate the whole Stream?

    - by abhin4v
    In Scala, does calling isEmtpy method on an instance of Stream class cause the stream to be evaluated completely? My code is like this: import Stream.cons private val odds: Stream[Int] = cons(3, odds.map(_ + 2)) private val primes: Stream[Int] = cons(2, odds filter isPrime) private def isPrime(n: Int): Boolean = n match { case 1 => false case 2 => true case 3 => true case 5 => true case 7 => true case x if n % 3 == 0 => false case x if n % 5 == 0 => false case x if n % 7 == 0 => false case x if (x + 1) % 6 == 0 || (x - 1) % 6 == 0 => true case x => primeDivisors(x) isEmpty } import Math.{sqrt, ceil} private def primeDivisors(n: Int) = primes takeWhile { _ <= ceil(sqrt(n))} filter {n % _ == 0 } So, does the call to isEmpty on the line case x => primeDivisors(x) isEmpty cause all the prime divisors to be evaluated or only the first one?

    Read the article

  • Will JavaScript evaluate a property's value if it's not part of an assignment statement?

    - by Bungle
    I've come across a fairly obscure problem having to do with measuring a document's height before the styling has been applied by the browser. More information here: http://sonspring.com/journal/jquery-iframe-sizing http://ajaxian.com/archives/safari-3-onload-firing-and-bad-timing In Dave Hyatt's comment from June 27, he advises simply checking the document.body.offsetLeft property to force Safari to do a reflow. Can I simply use the following statement: document.body.offsetLeft; or do I need to assign it to a variable, e.g.: var force_layout = document.body.offsetLeft; in order for browsers to calculate that value? I think this comes down to a more fundamental question - that is, without being part of an assignment statement, will JavaScript still evaluate a property's value? Does this depend on whether a particular browser's JavaScript engine optimizes the code?

    Read the article

  • How does a Java Arraylist contains() method evalute objects?

    - by mvid
    Say i create one object and add it to my ArrayList. If I then create another object with exactly the same constructor input, will the contain() method evaluate the two objects to be the same? Assume the constructor doesn't do anything funny with the input, and the variables stored in both objects are identical. ArrayList<Thing> basket = new ArrayList<Thing>(); Thing thing = new Thing(100); basket.add(thing); Thing another = new Thing(100); basket.contains(another); // true or false?

    Read the article

  • How do you do dynamic script evaluation in C#?

    - by Deane
    What is the state of dynamic code evaluation in C#? For a very advanced feature of an app I'm working on, I'd like the users to be able to enter a line of C# code that should evaluate to a boolean. Something like: DateTime.Now.Hours > 12 && DateTime.Now.Hours < 14 I want to dynamically eval this string and capture the result as a boolean. I tried Microsoft.JScript.Eval.JScriptEvaluate, and this worked, but it's technically deprecated and it only works with Javascript (not ideal, but workable). Additionally, I'd like to be able to push objects into the script engine so that they can be used in the evaluation. Some resources I find mentioned dynamically compiling assemblies, but this is more overhead than I think I want to deal with. So, what is the state of dynamic script evaluation in C#? Is it possible, or am I out of luck?

    Read the article

  • Piwik Web Analytics - Anyone with experience of it?

    - by Phil.Wheeler
    I'm considering trying to get more granular analytics for my sites than the free plan on my current provider, Clicky, provides. Piwik looks like a strong contender in the analytics space (and I'm surprised I haven't heard about it before) but I want to be sure I'm not throwing the baby out with the bathwater by swapping to it. Does anyone have any experience with this software and - in particular - are there any people out there who've tried customising the code or developing their own plugin?

    Read the article

  • Whats the point of lazy-seq in clojure?

    - by dbyrne
    I am looking through some example Fibonacci sequence clojure code: (def fibs (lazy-cat [1 2] (map + fibs (rest fibs)))) I generally understand what is going on, but don't quite understand the point of lazy-cat. I know that lazy-cat is a macro that is translating to something like this: (def fibs (concat (lazy-seq [1 2]) (lazy-seq (map + fibs (rest fibs))))) What exactly is lazy-seq accomplishing? It would still be evaluated lazily even without lazy-seq? Is this strictly for caching purposes?

    Read the article

  • Changing text depending on rounded total from database

    - by NeonBlue Bliss
    On a website I have a number of small PHP scripts to automate changes to the text of the site, depending on a figure that's calculated from a MySQL database. The site is for a fundraising group, and the text in question on the home page gives the total amount raised. The amount raised is pulled from the database and rounded to the nearest thousand. This is the PHP I use to round the figure and find the last three digits of the total: $query4 = mysql_query("SELECT SUM(amountraised) AS full_total FROM fundraisingtotal;"); $result4 = mysql_fetch_array($query4); $fulltotal = $result4["full_total"]; $num = $fulltotal + 30000; $ftotalr = round($num,-3); $roundnum = round($num); $string = $roundnum; $length = strlen($string); $characters = 3; $start = $length - $characters; $string = substr($string , $start ,$characters); $figure = $string; (£30,000 is the amount that had been raised by the previous fundraising team from when the project first started, which is why I've added 30000 to $fulltotal for the $num variable) Currently the text reads: the bookstall and other fundraising events have raised more than &pound;<? echo number_format($ftotalr); ?> I've just realised though that because the PHP is rounding to the nearest thousand, if the total's for example £39,200 and it's rounded to £40,000, to say it's more than £40,000 is incorrect, and in that case I'd need it to say 'almost £40,000' or something similar. I obviously need to replace the 'more than' with a variable. Obviously I need to test whether the last three digits of the total are nearer to 0 or 1000, so that if the total was for example £39,2000, the text would read 'just over', if it was between £39,250 and £39,400 something like 'over', between £39,400 and £39,700 something like 'well over', and between £39,700 and £39,999, 'almost.' I've managed to get the last three digits of the total as a variable, and I think I need some sort of an if/else/elseif code block (not sure if that would be the right approach, or whether to use case/break), and obviously I'm going to have to check whether the figure meets each of the criteria, but I can't figure out how to do that. Could anyone suggest what would be the best way to do this please?

    Read the article

  • Truly declarative language?

    - by gjvdkamp
    Hi all, Does anyone know of a truly declarative language? The behaviour I'm looking for is kind of what Excel does, where I can define variables and formulas, and have the formula's result change when the input changes (without having set the answer again myself) The behaviour I'm looking for is best shown with this pseudo code: X = 10 // define and assign two variables Y = 20; Z = X + Y // declare a formula that uses these two variables X = 50 // change one of the input variables ?Z // asking for Z should now give 70 (50 + 20) I've tried this in a lot of languages like F#, python, matlab etc, but every time i try this they come up with 30 instead of 70. Wich is correct from an imperative point of view, but i'm looking for a more declerative behaviour if you know what i mean. And this is just a very simple calculation. When things get more difficult it should handle stuff like recursion and memoization automagically. The code below would obviously work in C# but it's just so much code for the job, i'm looking for something a bit more to the point without all that 'technical noise' class BlaBla{ public int X {get;set;} // this used to be even worse before 3.0 public int Y {get;set;} public int Z {get{return X + Y;}} } static void main(){ BlaBla bla = new BlaBla(); bla.X = 10; bla.Y = 20; // can't define anything here bla.X = 50; // bit pointless here but I'll do it anyway. Console.Writeline(bla.Z);// 70, hurray! } This just seems like so much code, curly braces and semicolons that add nothing. Is there a language/ application (apart from Exel) that does this? Maybe I'm no doing it right in the mentioned langauges, or I've completely missed an app that does just this. I prototyped a language/ application that does this (along with some other stuff) and am thinking of productizing it. I just can't believe it's not there yet. Don't want to waste my time. Thanks in advance, Gert-Jan

    Read the article

  • By-name repeated parameters

    - by Green Hyena
    How to pass by-name repeated parameters in Scala? The following code fails to work: scala> def foo(s: (=> String)*) = { <console>:1: error: no by-name parameter type allowed here def foo(s: (=> String)*) = { ^ Is there any other way I could pass a variable number of by name parameters to the method?

    Read the article

  • Aligning music notes using String matching algorithms or Dynamic Programming

    - by Dolphin
    Hi I need to compare 2 sets of musical pieces (i.e. a playing-taken in MIDI format-note details extracted and saved in a database table, against sheet music-taken into XML format). When evaluating playing against sheet music (i.e.note details-pitch, duration, rhythm), note alignment needs to be done - to identify missed/extra/incorrect/swapped notes that from the reference (sheet music) notes. I have like 1800-2500 notes in one piece approx (can even be more-with polyphonic, right now I'm doing for monophonic). So will I have to have all these into an array? Will it be memory overloading or stack overflow? There are string matching algorithms like KMP, Boyce-Moore. But note alignment can also be done through Dynamic Programming. How can I use Dynamic Programming to approach this? What are the available algorithms? Is it about approximate string matching? Which approach is much productive? String matching algos like Boyce-Moore, or dynamic programming? How can I assess which is more effective? Greatly appreciate any insight or suggestions Thanks in advance

    Read the article

  • Any merit to a lazy-ish juxt function?

    - by NielsK
    In answering a question about a function that maps over multiple functions with the same arguments (A: juxt), I came up with a function that basically took the same form as juxt, but used map: (defn could-be-lazy-juxt [& funs] (fn [& args] (map #(apply %1 %2) funs (repeat args)))) => ((juxt inc dec str) 1) [2 0 "1"] => ((could-be-lazy-juxt inc dec str) 1) (2 0 "1") => ((juxt * / -) 6 2) [12 3 4] => ((could-be-lazy-juxt * / -) 6 2) (12 3 4) As posted in the original question, I have little clue about the laziness or performance of it, but timing in the REPL does suggest something lazy-ish is going on. => (time (apply (juxt + -) (range 1 100))) "Elapsed time: 0.097198 msecs" [4950 -4948] => (time (apply (could-be-lazy-juxt + -) (range 1 100))) "Elapsed time: 0.074558 msecs" (4950 -4948) => (time (apply (juxt + -) (range 10000000))) "Elapsed time: 1019.317913 msecs" [49999995000000 -49999995000000] => (time (apply (could-be-lazy-juxt + -) (range 10000000))) "Elapsed time: 0.070332 msecs" (49999995000000 -49999995000000) I'm sure this function is not really that quick (the print of the outcome 'feels' about as long in both). Doing a 'take x' on the function only limits the amount of functions evaluated, which probably is limited in it's applicability, and limiting the other parameters by 'take' should be just as lazy in normal juxt. Is this juxt really lazy ? Would a lazy juxt bring anything useful to the table, for instance as a compositing step between other lazy functions ? What are the performance (mem / cpu / object count / compilation) implications ? Is that why the Clojure juxt implementation is done with a reduce and returns a vector ? Edit: Somehow things can always be done simpler in Clojure. (defn could-be-lazy-juxt [& funs] (fn [& args] (map #(apply % args) funs)))

    Read the article

  • RAII: Initializing data member in const method

    - by Thomas Matthews
    In RAII, resources are not initialized until they are accessed. However, many access methods are declared constant. I need to call a mutable (non-const) function to initialize a data member. Example: Loading from a data base struct MyClass { int get_value(void) const; private: void load_from_database(void); // Loads the data member from database. int m_value; }; int MyClass :: get_value(void) const { static bool value_initialized(false); if (!value_initialized) { // The compiler complains about this call because // the method is non-const and called from a const // method. load_from_database(); } return m_value; } My primitive solution is to declare the data member as mutable. I would rather not do this, because it suggests that other methods can change the member. How would I cast the load_from_database() statement to get rid of the compiler errors?

    Read the article

  • Haskell lazy I/O and closing files

    - by Jesse
    I've written a small Haskell program to print the MD5 checksums of all files in the current directory (searched recursively). Basically a Haskell version of md5deep. All is fine and dandy except if the current directory has a very large number of files, in which case I get an error like: <program>: <currentFile>: openBinaryFile: resource exhausted (Too many open files) It seems Haskell's laziness is causing it not to close files, even after its corresponding line of output has been completed. The relevant code is below. The function of interest is getList. import qualified Data.ByteString.Lazy as BS main :: IO () main = putStr . unlines =<< getList "." getList :: FilePath -> IO [String] getList p = let getFileLine path = liftM (\c -> (hex $ hash $ BS.unpack c) ++ " " ++ path) (BS.readFile path) in mapM getFileLine =<< getRecursiveContents p hex :: [Word8] -> String hex = concatMap (\x -> printf "%0.2x" (toInteger x)) getRecursiveContents :: FilePath -> IO [FilePath] -- ^ Just gets the paths to all the files in the given directory. Are there any ideas on how I could solve this problem? The entire program is available here: http://haskell.pastebin.com/PAZm0Dcb

    Read the article

  • Is it possible to match with decomposed sequences in F#?

    - by Ball
    I seem to remember an older version of F# allowing structural decomposition when matching sequences just like lists. Is there a way to use the list syntax while keeping the sequence lazy? I'm hoping to avoid a lot of calls to Seq.head and Seq.skip 1. I'm hoping for something like: let decomposable (xs:seq<'a>) = match xs with | h :: t -> true | _ -> false seq{ 1..100 } |> decomposable But this only handles lists and gives a type error when using sequences. When using List.of_seq, it seems to evaluate all the elements in the sequence, even if it is infinite.

    Read the article

  • Best Functional Approach

    - by dbyrne
    I have some mutable scala code that I am trying to rewrite in a more functional style. It is a fairly intricate piece of code, so I am trying to refactor it in pieces. My first thought was this: def iterate(count:Int,d:MyComplexType) = { //Generate next value n //Process n causing some side effects return iterate(count - 1, n) } This didn't seem functional at all to me, since I still have side effects mixed throughout my code. My second thought was this: def generateStream(d:MyComplexType):Stream[MyComplexType] = { //Generate next value n return Stream.cons(n, generateStream(n)) } for (n <- generateStream(initialValue).take(2000000)) { //process n causing some side effects } This seemed like a better solution to me, because at least I've isolated my functional value-generation code from the mutable value-processing code. However, this is much less memory efficient because I am generating a large list that I don't really need to store. This leaves me with 3 choices: Write a tail-recursive function, bite the bullet and refactor the value-processing code Use a lazy list. This is not a memory sensitive app (although it is performance sensitive) Come up with a new approach. I guess what I really want is a lazily evaluated sequence where I can discard the values after I've processed them. Any suggestions?

    Read the article

  • What is the purpose of OCaml's Lazy.lazy_from_val?

    - by Ricardo
    The doc of Lazy.lazy_from_val states that this function is for special cases: val lazy_from_val : 'a -> 'a t lazy_from_val v returns an already-forced suspension of v This is for special purposes only and should not be confused with lazy (v). Which cases are they talking about? If I create a pair of suspended computation from a value like: let l1 = lazy 123 let l2 = Lazy.lazy_from_val 123 What is the difference between these two? Because Lazy.lazy_is_val l1 and Lazy.lazy_is_val l2 both return true saying that the value is already forced!

    Read the article

  • Coping with feelings of technical mediocrity

    - by Karim
    As I've progressed as a programmer, I noticed more nuance and areas I could study in depth. In part, I've come to think of myself from, at one point, a "guru" to now much less, even mediocre or inadequate. Is this normal, or is it a sign of a destructive excessive ambition? Background I started to program when I was still a kid, I had about 10 or 11 years. I really enjoy my work and never get bored from it. It's amazing how somebody could be paid for what he really likes to do and would be doing it anyway even for free. When I first started to program, I was feeling proud of what I was doing, each application I built was for me a success and after 2-3 year I had a feeling that I'm a coding guru. It was a nice feeling. ;-) But the more I was in the field and the more types of software I started to develop, I was starting to have a feeling that I'm completely wrong in thinking I'm a guru. I felt that I'm not even a mediocre developer. Each new field I start to work on is giving me this feeling. Like when I once developed a device driver for a client, I saw how much I need to learn about device drivers. When I developed a video filter for an application, I saw how much do I still need to learn about DirectShow, Color Spaces, and all the theory behind that. The worst thing was when I started to learn algorithms. It was several years ago. I knew then the basic structures and algorithms like the sorting, some types of trees, some hashtables, strings, etc. and when I really wanted to learn a group of structures I learned about 5-6 new types and saw that in fact even this small group has several hundred subtypes of structures. It's depressing how little time people have in their lives to learn all this stuff. I'm now a software developer with about 10 years of experience and I still feel that I'm not a proficient developer when I think about things that others do in the industry.

    Read the article

< Previous Page | 3 4 5 6 7 8 9 10 11 12 13 14  | Next Page >