function,dictionary,f#,immutability,mutable , F# - Function not returning updated data


F# - Function not returning updated data

Question:

Tag: function,dictionary,f#,immutability,mutable

I have a function GetCars which does not return the updated state. If I add a parameter, it works fine, or if I execute the same code in the other functions it works fine.

open System
open System.Collections.Concurrent

type Car = {
    Make : string
    Model : string
    ID : int
}

type Cars = {
    Count : int
    Collection : Car[]
}

module AppState = begin
    let state = new ConcurrentDictionary<string, obj>()

    let added = state.TryAdd("cars", {
        Count = 1
        Collection = [| { Make = "Honda"; Model = "Civic"; ID = 0 } |]
    })

    let DownCastCars (o : obj) =
        match o with
        | :? Cars as cars -> Some(cars)
        | _ -> None

    let GetCars = 
        let mutable cars : obj = null; 
        let success = state.TryGetValue("cars", &cars)
        if success then
            DownCastCars cars
        else
            None

    let AddCar car =
        match GetCars with
        | Some cars -> 
            state.TryUpdate("cars", { cars with Collection = Array.append cars.Collection [| car |] }, cars)
        | None ->
            false
end

let AddCarMakeModel make model =
    let car : Car = {
        Make = make
        Model = model
        ID = match AppState.GetCars with
                | Some cars -> cars.Collection.Length
                | None -> 0
    }
    let success = AppState.AddCar car
    if success then
        printfn "Successfully added car :)"
    else
        printfn "Failed to add car :("

[<EntryPoint>]
let main argv = 
    AddCarMakeModel "Honda" "Civic"
    AddCarMakeModel "Honda" "Civic LX"
    printfn "Press any key to continue"
    let s = Console.ReadLine()
    0 // return an integer exit code

If I add a parameter to GetCars i.e

let GetCars notused = 
    let mutable cars : obj = null; 
    let success = state.TryGetValue("cars", &cars)
    if success then
        DownCastCars cars
    else
        None

Then the GetCars function will return the newest value every time. Or if I just place the same code inside the other methods I am using i.e

let AddCarMakeModel Make Model =
    let car : Car = {
        Make = make
        Model = model
        ID = match AppState.GetCars with
                | Some cars -> cars.Collection.Length
                | None -> 0
    }
    let success = AppState.AddCar car
    if success then
        printfn "Successfully added car :)"
    else
        printfn "Failed to add car :("

I am guessing this has to do with "Do Bindings" but I am not sure how to apply that successfully to GetCars. I did notice GetCars get called when the application starts, and if I set a break point inside the function it never gets that far again.


Answer:

As already stated in the comments, the solution is to add a unit parameter.

The problem is that you are declaring a constant value, not a function value.

This is evident if you look at its signature: val GetCars : Cars option There is no arrow, just a value, so GetCars will be executed only once and bound to the value on the right side of the expression.

By adding a unit parameter you get the signature: val GetCars : unit -> Cars option so now at the call site you can refer either to the function value by GetCars alone or to execute it and get its result by GetCars().

Also note you don't need the mutable since F# treat functions returning a value and a ref as a tuple, you can write GetCars like this:

let GetCars() = 
    match state.TryGetValue("cars") with
    | true, (:? Cars as cars) -> Some cars
    | _ -> None

And then get rid of the function DownCastCars.


Related:


JavaScript recursive function breaks when () included in call


javascript,jquery,function
I have created a countdown "Pomodoro" timer using JavaScript and JQuery. The code snippet I am referring to is the following: var time = 1500; var cycle = "long"; var tracker = 0; var paused = false; //Timer countdown function function countdown(){ if (!paused) { var seconds = ("00" +...

Can't understand this Javascript function (function overloading)


javascript,function,methods,overloading
I'm reading Secrets of Javascript Ninja and came across an example that I cannot fully understand. This same example was cited by some other user here before, but their doubts are different than mine. Here is the example: function addMethod(object, name, fn) { var old = object[name]; object[name] = function(){...

Template C++: How to access iterator value for both std::map and std::set?


c++,templates,dictionary,stl,set
I have a specific search function. Because it's used on both std::set and std::map, it was duplicated in our code (not using template). I have to maintain those two functions, and I'd like to move them to a single function using a template (and then have only one search preocedure...

ValueError: dictionary update sequence element #0 has length 1; 2 is required while reading from file


python,file,dictionary
I'm trying to read a dictionary off a file and then make the string into a dictionary. I have this, with open("../resources/enemyStats.txt", "r") as stats: for line in stats: if self.kind in line: line = line.replace(self.kind + " ", "") line = dict(line) return line and the line in the...

sum of Digits through Recursion


java,function,recursion,sum,digit
I am trying to make a recursive function which should return the sum of digits. The function should have only one argument. So far I have this; public int sumDigits(int n) { if(n%10 == n) // last digit remains return n; else{ int rightdigit; rightdigit = n%10; // taking out...

How to pass pointer to struct to a function?


c,function,pointers,struct
I am instantiating the struct within the main() function and I am passing a pointer to this structure over to a function. I would like to then pass this pointer to the original struct to another function, how would I do this? I am now lost in pointerception. struct coords...

session value in javascript cannot be set


javascript,function,session
I am quite new to javascript, I wonder why my session value in javascript wont be set to 1 even I tried. When call this function again, the value of the session will change again. My javascript code as below. <script type="text/javascript"> function Confirm() { alert(<%=Session["Once"]%> != 1); var value...

Interpret formulae/operators as functions


r,function,variable-assignment,formula,evaluation
Is it possible in R to assign custom functions to mathematical operators (eg. *, +) or interpret the formulae supplied with as.formula() as a directive to evaluate? Specifically, I would like * to be interpretted as intersect(), and + as c(), so R would evaluate the expression (a * (b...

Stopping condition on a recursive function - Haskell


string,function,haskell,if-statement,recursion
So, I have this function which aims to align the text on the left without cutting words(only white spaces). However my problem is that I cannot find a stopping condition of the function and it goes infinitely. f n "" = "" --weak condition f n s = if n...

How to find exact place for given value in python dictionary?


python,dictionary
I have one dictionary with key and value. Key is row name and values is the last seat number. I would like to find the row number based on the input value. seats_dict={'A':10,'B':'20':'C':30} Input: seat_num =16 Output: Should be 'B' Is there any function to identity this in python?...

Decremented value called in the recursion in Haskell


string,function,haskell,recursion,parameters
So, I have this function that aligns the text to the left for a given column width. I have already fixed some of its problems, but I am unable to make it not use the decremented parameter once it is called, but to return to the starting value of n....

How does ((a++,b)) work? [duplicate]


c,function,recursion,comma
This question already has an answer here: What does the comma operator `,` do in C? 8 answers In the below block of code, I am trying to understand how the line return reverse((i++, i)) is working. #include <stdio.h> void reverse(int i); int main() { reverse(1); } void reverse(int...

Compiler modifying a variable without adressing it


c#,variables,dictionary
In my program I found that when asssigning a variable to another, modifying the first one, also modifies the second. Example: using System; using System.Collections.Generic; using System.Windows.Forms; namespace Dict_test { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void TestButton_Click(object sender, EventArgs e) { Dictionary<string,...

Toggle text + also call method with argument?


jquery,function,toggle
Im trying to toggle change a text on spacebar press with jquery ( works ) but also try to call a method with custom argument. How would below code example needs to me modified to do this? I have tried all kinds of ways but don't understand how to add...

Call known function (with parameters) in class whose name is defined by string variable


java,function,class,variables
I have a bunch of classes of various names and each has a performLogic function that accepts a number of preset parameters (always the same): public final class DoSomeAction extends SetupAction { public void performLogic(param1, param2... I want a way where I can call it like this: String actionName =...

Stuck on Structs(c++)


c++,function,struct
Okay so this is what Ive been asked to do "make a struct called Coordinate that contains the latitude and longitude of a point on the surface of the Earth. The struct should also store a label or name for the coordinate (e.g., “Calgary”). Both the latitude and longitude member...

Python3 create files from dictionary


file,python-3.x,dictionary
I have a dictionary in a function which is called searchInMyDict(dict) for example. The dictionary included in that function has for key a group name and has for value a list of gene's functions. the dictionary looks like : {"OG_1": ["gene's functionA, gene's functionB, gene's functionC"] "OG_2": ["gene's functionM, gene's...

C++ need help figuring out word count in function. (Ex. Hello World = 2)


c++,function
I'm figuring out the algorithm on this function and it keeps crashing at runtime, here's the code snippet: int wordCounter(char usStr[]) { int index= 0, punct= 0; while(usStr[index]!= '\0') //If it's not the end of the sentence if(usStr[index]== ' ') //If it finds a space index++; while(usStr[index]== '\0') //If it's...

How do I check value in a nested dictionary in Python?


python,dictionary
Suppose we have a list of dictionaries listD where each dictionary is quite deeply nested with more dictionaries. e.g.suppose that the first element of listD is: listD[0] = {"bar1":{"bar2":{"bar3":1234}}} Now I want to check if listD[i]["bar1"]["bar2"]["bar3"] == 1234 for all i. For the first element where i = 0, this...

Python 3.4: List to Dictionary


python,list,python-3.x,dictionary
I have a string as follows : ['Total Revenue', 31821000, 30871000, 29904000, 'Cost of Revenue', 16447000, 16106000, 15685000, 'Gross Profit', 15374000, 14765000, 14219000, 'Research Development', 1770000, 1715000, 1634000, 'Selling General and Administrative', 6469000, 6384000, 6102000, 'Non Recurring', '-', '-', '-', 'Others', '-', '-', '-', 'Total Operating Expenses', '-', '-', '-',...

strip_tags() on MySQLi Query and PHP Function [closed]


php,mysql,string,function,mysqli
I'm trying hard to learn how to create functions, and I don't know what I'm doing wrong here. Could someone explain it to me please? I'm not using strip_tags(), why it's getting me this error? I don't need it to return, I just to need to update database if $xp...

SQL average age comparison function returns null


mysql,sql,function,datetime
So, I'm working in MySQL, writing a function that averages the ages of women and men from a table and compares them, and returns which is greater. Dates are in the format of YYYY-MM-DD, and I'm using DATEDIFF(). The function appears to work correctly, but when I run the script,...

JSLint won't recognize getElementById


javascript,function,getelementbyid,jslint
JSLint gives errors with simple function, running on brackets with JSLint. Javascript: function soundSorry() { getElementById("player").play(); } Error codes: 2 Missing 'use strict' statement. getElementById("player").play(); 2 'getElementById' was used before it was defined. getElementById("player").play(); Any ideas?...

Update input number variable onclick


javascript,jquery,html,function
I am trying to create a calculator style thing, where you put in how many years into a input, you hit submit and it gives you different results below without reloading the page. I have all the calculations working right now, but I just cant get the input number variable...

Selecting and removing a html select option without selecting by index or ID, using vanilla JavaScript


javascript,function,select,options
I need to remove an option on a select box, and I've figured out a potential solution in the code below, but it doesn't feel particularly 'safe' (if another developer decided to add an option to the backend, the option will re-appear). Is there a better way of achieving this...

Specific rows from CSV as dictionary and logic when keys are the same - Python


python,csv,dictionary
abc11 bvc ex 123 456 somestuffhere abc11 bvc ex 456 476 somestuffhere abc12 bvc ex 173 426 somestuffhere abc12 bvc ex 426 496 somestuffhere abc13 bvc ex 143 796 somestuffhere abc13 bvc ex 743 896 somestuffhere I am trying to put the above CSV file as a dictionary, {'abc11':['123','476'],'abc12':['173','496'],'abc13':['143','896']}. I...

My is_prime function fails on 9, and I don't know why?


python,function
I have a bit of a problem. I am writing an is_prime function on, but whenever I run it, it fails on is_prime(9), and I cannot see why: def is_prime(x): if x < 2: ##because negative numbers, 0 and 1 are not prime## return False elif x == 2: return...

Matching key/value pairs in two dictionaries and creating a third one


python,loops,dictionary
I have read two files from which I created dictionaries with IDs and their corresponding sequences as keys and values, respectively. I am trying to find the key/value pairs that exist in both dictionaries and to create a new one containing only these matching ones. Each dictionary has a couple...

Calling function and passing arguments multiple times


python,function,loops
I want to call the function multiple time and use it's returned argument everytime when it's called. For example: def myfunction(first, second, third): return (first+1,second+1,third+1) 1st call: myfunction(1,2,3) 2nd call is going to be pass returned variables: myfunction(2,3,4) and loop it until defined times. How can I do such loop?...

My function will log a value to the console, but it won't return the same value - why? [duplicate]


javascript,arrays,function,recursion
This question already has an answer here: Return value of recursive function is 'undefined' 1 answer I've created the following function to flatten a nested array: function steamroller(arr) { arr = arr.reduce(function(a, b, i){ return a.concat(b); },[]); if (!Array.isArray(arr[arr.length-1])) {console.log(arr); return arr;} steamroller(arr); } steamroller([1, [2], [3, [[4]]]]); The...

Counting bytes received by posix read()


c,function,serial-port,posix
I get confused with one line of code: temp_uart_count = read(VCOM, temp_uart_data, 4096); I found more about read function at http://linux.die.net/man/3/read, but if everything is okay it returns 0, so how we can get num of bytes received from that? temp_uart_count is used to count how much bytes we received...

How can I minimize this function in R?


r,function,optimization,mathematical-optimization
I'm attempting to write a formula that will determine a value of a that minimizes the function output myfun (i.e. a-fptotal). MWE: c <- as.matrix(c(.25,.5,.25)) d <- as.matrix(c(10000,12500,15000)) e <- 700 f <- 1.1 tr <- .30 myfun <- function(a) { b <- max(a-e,0) df <- data.frame(u1=c(c*b*.40),u2=c(c*b*.60)) df$year <- 1:nrow(df)...

Reaching into a nested dictionary several levels deep (that might not exist)


python,dictionary
I have an API that I call that returns a dictionary. Part of that dictionary is itself another dictionary. In that inside dictionary, there are some keys that might not exist, or they might. Those keys could reference another dictionary. To give an example, say I have the following dictionaries:...

Replace paragraph in HTML with new paragraph using Javascript


javascript,function,onload,getelementbyid,appendchild
I am attempting to replace a p in my HTML doc with a paragraph created in Javascript. Once the page loads, two will be replaced with t. var two = document.getElementById("two"); document.onload = function myFunction() { var p = document.createElement("p"); var t = document.createTextNode("I am the superior text"); p.appendChild(t); document.getElementById("p");...

jQuery - Value in Function


jquery,arrays,function
My array: array.name = "Thiago"; array.date = "01/01/1990"; I want a function like this: function myFunc( array, fieldToCompare, valueToCompare ) { if( array.fieldToCompare == "Thiago" ) alert(true); } myFunc( myArray, name, "Thiago" ); is it possible?...

Select / subset spatial data in R


r,dictionary,spatial
I am working on a large data set with spatial data (lat/long). My data set contains some positions that I don´t want in my analysis (it makes the files to heavy to process in ArcMap- many Go of data). This is why I want to subset the relevant data for...

Is it possible to use $(this) in a function called from another function?


jquery,function,this
Sorry for the question title, I know it's not very well worded, but I couldn't really explain what I'm asking in a summary. I have a JQuery function tied to the click event of an element. For reasons that may well be flawed (other than making more sense to me...

Replace a list item with the value of the item stored in dictionary in python


python,dictionary
I have a list and a dictionary and I want to replace the list item with the value of the dictionary. A simplified version of my problem is as follows: #This is a list a=['dog', 'cat', 'cow'] #This is a dictionary b={'dog': 'barks', 'cat': 'meows', 'cow': 'moos' } Now list...

PercentOfSum(fld, condfld) SSRS Equivalent


function,reporting-services,crystal-reports,ssrs-2008,ssrs-2008-r2
Crystal Reports has a built-in function PercentOfSum(fld, condfld) (documentation here). How can I achieve the same functionality in SSRS?

How to skip a function


function,python-2.7
I am learning python and trying to make a little game. So my question is can you define a function but skip it and use it later. EX. def func() print"1,2,3,4" func() def func2() print "counting" func() func2() How would I skip func but still be able to print it...

XQuery - Doing math on elements within a sequence and aggregating results


function,operators,xquery,sequence,aggregation
I'm trying to execute a XQuery sum function in a multiplication of two XML elements, but it has been difficult to avoid the iteration in a sequence of elements. For example, consider this case: sample data: <Orders> <Order> <OrderKey>1</OrderKey> <LineItem> <LineNumber>1</LineNumber> <Quantity>41</Quantity> <ExtendedPrice>70848.0000</ExtendedPrice> <Discount>0.0913</Discount> <Tax>0.0663</Tax> <ReturnFlag>A</ReturnFlag>...

Python RuntimeError: maximum recursion depth exceeded in cmp


python,list,dictionary,recursion
I have a complex data structure that I'm trying to process. Explanation of the data structure: I have a dictionary of classes. The key is a name. The value is a class reference. The class contains two lists of dictionaries. Here's a simple example of my data structure: import scipy.stats...

PHP / MySQL: How to store Select results in array


php,mysql,arrays,dictionary,key
I am new to PHP and MySQL and hope someone can help me with this. I have a MySql db with a table "TranslationsMain" and the following PHP query. This returns all the items from column "German" (incl. the corresponding ID) from the db table and works correctly so far....

is return main(); a valid syntax?


c,function,return,language-lawyer,return-type
I found some interesting code lines: #include <stdio.h> int main() { printf("Hi there"); return main(); } It compiles ok (VS2013) and ends up in stackoverflow error because of the recursive call to main(). I didn't know that the return statement accepts any parameter that can be evaluated to the expected...

Python avoid item = None in a request of multiple items


python,function,request,urllib,nonetype
I'm doing a loop for multiple requests on a web database, each time it takes one geneId to request it to the database. If the geneId is referenced I can use the data I get for another request on a second database. But if the geneId is not referenced, it...

How can I simulate a nested function without lambda expressions in C++11?


c++,function,c++11,lambda,allegro
I have the following code: int main(int argc, char **argv) { App app(800, 600); app.add_event_scene(Scene("Event Plot", event_plot)); Image x("sample.png"); struct foo { static void visual_plot() { x.draw(); } }; // Error. app.add_visual_scene(Scene("Visual Plot", foo::visual_plot)); app.run(); return 0; } And I get the following error: ||=== Build: Debug in Joy-Plus-Plus (compiler:...

Why can we use undefined object in Javascript function declaration?


javascript,function
Chromium WebUI has a cr.js file, which offers cr.define( name, fun ) method, for modulization. All the porperties of the object that fun returns, will be added to the name namescope object. In chromium browser bookmarks manager page(chrome://bookmarks), a Javascript source file named bmm.js is loaded. This is a Javascript...

MySQL function with parameters syntax error


mysql,regex,function
I'm trying to convert this query to a MySQL function SET @v1 := ( SELECT count(id) as count FROM article_category where (title like "About Usd") or (title like "About Usd-%" and title regexp '[0-9]$') ); INSERT INTO `article_category` (`title`,`meta_data`,`meta_description`) VALUES ( IF(@v1 <= 0, "About Usd", CONCAT("About Usd","-",@v1) ), "ddddD",...

Implementing a dictionary function to calculate the average of a list


python,list,dictionary
As always, I've attempted this for awhile before I proceed to ask a question on here. I know there are several attempts at answering this, but none really worked for what I needed. Here are the instructions: Implement the following three functions (you should use an appropriate looping construct to...

Compare dictionary key, values with nested list elements - Python


python,dictionary,nested-lists
Trying to match key, values in dictionaries with nested list elements dict = {'a':[1, 5], 'c':[7, 9], 'f':[10, 12], 'b':[15, 20]} list_A = [['a', '4'], ['a', '7'], ['b', '17'], ['b', 10], ['c', '7'], ['d', '7'], ['f', '11'], ['f', '12']] list_A_no_reps =['a', 'b', 'c', 'd', 'f'] I am trying to get...