I'm trying to do a cyclic graph in F#

My node type looks something like this:

```
type Node = { Value : int; Edges : Node list }
```

My question is: Do I need to make Edges mutable in order to have cycles?

Tag: graph,f#,immutability,mutability

I'm trying to do a cyclic graph in F#

My node type looks something like this:

```
type Node = { Value : int; Edges : Node list }
```

My question is: Do I need to make Edges mutable in order to have cycles?

F# makes it possible to create immediate recursive object references with cycles, but this really only works on (fairly simple) records. So, if you try this on your definition it won't work:

```
let rec loop =
{ Value = 0;
Edges = [loop] }
```

However, you can still avoid mutation - one reasonable alternative is to use lazy values:

```
type Node = { Value : int; Edges : Lazy<Node list>}
```

This way, you are giving the compiler "enough time" to create a `loop`

value before it needs to evaluate the edges (and access the `loop`

value again):

```
let rec loop =
{ Value = 0;
Edges = lazy [loop] }
```

In practice, you'll probably want to call some functions to create the edges, but that should work too. You should be able to write e.g. `Edges = lazy (someFancyFunction loop)`

.

Alternatively, you could also use `seq<Edges>`

(as sequences are lazy by default), but that would re-evaluate the edges every time, so you probably don't want to do that.

Aside from Patryk's point on comment: It's a really imperative problem so it will not get much prettier. The only thing I would try to change is the repeated read/writes - maybe like this: let copyInto (outstream : System.IO.Stream) (stream : System.IO.Stream) = let bufferLen : int = 4096 let...

I'm not sure what is the best way to define Unit for usage from C#. It might differ from how this is done in F# (because in F#, the compiler hides the usage in a way). However, you can actually find the implementation of F# unit in the core library:...

You should use bigint for large numbers, like this [1I..1234567I] |> List.filter (fun x -> x % 3I * x % 5I = 0I) |> List.sum or (less readable) [bigint 1..bigint 1234567] |> List.filter (fun x -> x % bigint 3 * x % bigint 5 = bigint 0) |>...

Both of your links are to the 'development' part of networkx (check the url), so I don't think it's in the standard release yet. Probably your best option is to copy the relevant code into a file in your working directory and import it separately. Otherwise, look to download the...

scala,f#,functional-programming,tail-recursion,continuation-passing

The second call to go on line 4 is not in tail position, it is wrapped inside an anonymous function. (It is in tail position for that function, but not for go itself.) For continuation passing style you need Proper Tail Calls, which Scala unfortunately doesn't have. (In order to...

c++,class,c++11,data-structures,graph

I advise you to use a Link structure, to represent an edge in the graph: struct Link { Node *N; float weight; } Then each Node can contain vector<Link> neighbors; This way there is no duplication of Nodes. There is a duplication of weights, since if Node A has a...

This is usually a sign that you should update your mono. Older mono versions have issues with their unzip implementation

As there's no code-behind you can't call the method from XAML but need to attach it from the outside: let AboutStack_MouseRightButtonDown args = // do whatever you want, return unit wnd.MouseRightButtonDown.Add(AboutStack_MouseRightButtonDown) or e.g. wnd.MouseRightButtonDown.Add(fun _ -> MessageBox.Show("Click!") |> ignore) Another approach would be to use a model (DataContext) and bindings...

It sounds like you’re taking the shortest path from wherever you find yourself currently, and not calculating the total distance to get to a node. Let’s step through it in detail. Dijkstra’s algorithm sets up two sets of nodes: visited (with known distances) and unvisited (with tentative distances). We start...

Which part of that statement do you find surprising? That parts of a single async can execute on different threadpool threads, or that a threadpool thread is necessarily being released and obtained on each bind? If it's the latter, then I agree - it sounds wrong. Looking at the code,...

If and only if, at some point during kahn's algorithm has no source to choose (and the remaining graph is still none empty), there is a cycle Proof: Direction1 <--: If there is a cycle, let it be v1->v2->v3->vk->v1. At each step of the algorithm, none of v1,v2,...,vk is a...

python,csv,matplotlib,graph,plot

you need to turn x and y into type np.array before you calculate above_threshold and below_threshold, and then it works. In your version, you don't get an array of bools, but just False and True. I added comma delimiters to your input csv file to make it work (I assume...

Replacing the following code: if(movei == (N*N)+1){ return true; } ...with a hardcoded value... if(movei == 62){ return true; } ...gave me a good result after 0.1 seconds. (A field with only three "zeroes" remaining.) So your overall algorithm works. Hint for better looks of the output: #include <iomanip> cout...

The first optimization is to read the whole file in memory in one shot. Accessing memory in the loops will be faster than calling fread. The second optimization is to do less arythmetic operations, even if it means more code. Third optimization is treating the data from file as characters...

Basically you can model it using each city/airport as a node and the flights as the connections in between. The weight of the connections/flights is then the time. If you assume that all stopovers are 30 minutes (in a simplified model) then you can add an additional cost per visited...

Your operator takes an arg of type obj so you should define it as a standalone function, not a type member. let (&?) (value:obj) (defaultValue:'a) = match value with | null -> defaultValue | _ -> unbox value Now you can do this: let voltage = m.["VoltageCaps"] &? 0 I...

This is a common mistake when coming from an OO language: there are no subtypes involved in this code. The fact that you named your union cases the same as the type of the field they contain can make this confusing though, so let me give a slightly different example:...

Performing a lookup into the list (as well as getting the length of the list) is not very efficient, because the library needs to iterate over the entire list (or over the first N elements). For this reason, doing this is not really idiomatic in F#. You can still keep...

What happens is that Doc.AsPagelet adds a wrapper around the doc, so you are adding an event listener to that wrapper. And even if it did not, you would be adding an event listener to the Div0 you created instead of the CheckBox itself. That being said, there are two...

In set theory notation |A| is the cardinality of set A, in other words the number of elements contained in set A. For Reference: http://www.mathsisfun.com/sets/symbols.html...

No, there shouldn't be an infinite cycle. Visited and unvisited nodes in the graph are kept track of, and a visited node will never be visited again. In your example: Mark all nodes as unvisited, except for the starting node which is visited Starting with A, visit B, mark B...

Here is the graph I propose: Two kinds of vertices: departure vertex: airport+departure time arrival vertex: airport + arrival time. Two kind of edges: flight edge: from a departure vertex to an arrival vertex wait edge: from an arrival vertex to a departure vertex of later time in the same...

I can think of one reason why async code would call another async block, which is that it lets you dispose of resources earlier - when the nested block completes. To demonstrate this, here is a little helper that prints a message when Dispose is called: let printOnDispose text =...

python,graph,dataframes,networkx

You could use B.add_weighted_edges_from( [(row['domain'], row['subdomain'], 1) for idx, row in df.iterrows()], weight='weight') to add weighted edges, or you could use B.add_edges_from( [(row['domain'], row['subdomain']) for idx, row in df.iterrows()]) to add edges without weights. You may not need weights since the node degree is the number of edges adjacent to...

algorithm,graph,tree,runtime,big-o

Don't know if your algorithm is correct, but it doesn't seem O(|V|) at least, because getting the "smallest edge not in T" of a vertex cannot be done in O(1). The most usual way to add an edge e=(u, v) into a MST T is: Run a BFS in T...

If you're looking for something both pure and idiomatic F#, then you shouldn't be using an inheritance hierarchy in the first place. That's an object-oriented concept. In F#, you could model Employee like this, using algebraic data types: type HourlyData = { Name : string; Rate : int } type...

First, your Expression non-terminal has two identical productions: Expression: | IDENTIFIER ASSIGN Expression { ScalarAssignmentExpression($1, $3) } | IDENTIFIER ASSIGN Expression { ArrayAssignmentExpression($1, $3) } So there is absolutely no way for the parser to distinguish between them, and thus know which action to take. I suppose you can tell...

You may use a recursive procedure, e.g.: for (int i=0;i<Points.Count;i++) { // Paths[i] contains all paths from start to Point[i] Paths.Add(new List<List<list<int>>>()) ; } int startIndex= ... ; int targetIndex=... ; ProcessPoint(startIndex) ; That's all: you will get in Paths[startIndex] all possible paths. Select those ending at target. The recursive...

javascript,svg,d3.js,graph,charts

This isn't possible with D3. The axis component will generate an axis that corresponds to the associated range, i.e. to make it any particular size, you have to modify the output range of the associated scale. You can do this quite easily in a responsive manner though by computing the...

When you use F# interactive, you first need to evaluate the code that defines the functions that you want to use. So, if you select just the last line of your script, you get an error. I suppose you are using Alt+Enter to send the code to F# interactive -...

IIUC, this is the classic Minimum Vertex Cover problem, which is, unfortunately, NP Complete. Fortunately, the most intuitive and greedy possible algorithm is as good as it gets in this case....

I'll maintain that this is a duplicate, but here's the exact code you need to get going: let inline getAllIds< ^a when ^a : not struct> (table : Table< ^a>) = table |> Seq.map (fun x -> (^a : (member Id : Guid with get) x)) Alternatively, the following syntax...

python,numpy,matplotlib,graph,plot

You can use the condition z=='some tag' to index the x and y array Here's an example (based on the code in your previous question) that should do it. Use a set to automate the creation of tags: import csv import datetime as dt import numpy as np import matplotlib.pyplot...

If you try to compile the first version, and then use e.g. Reflector to decompile it to C#, you'll see that the stack member is defined like this: public class Interp { public Stack<int> stack { get { return new Stack<int>(); } } // Other members omitted for clarity... }...

Instead of using xlabel and ylabel, you may want to go with set label. For example, #!/usr/local/bin/gnuplot datafile='tmp.dat' # file to plot set xlabel " " # no x-label set ylabel " " # no y-label # assuming all plots have same x and y range set xrange [-2:2] set...

templates,f#,visual-studio-2015

That's a bug in 2015 RC. It's already fixed, but we need to wait for another release. https://github.com/Microsoft/visualfsharp/issues/411

python,sql,r,graph,connected-components

In R, you could use the package igraph: library(igraph) gg <- graph.edgelist(as.matrix(d), directed=F) split(V(gg)$name, clusters(gg)$membership) #$`1` #[1] "a" "b" "c" "u" "e" # #$`2` #[1] "f" "g" "h" "j" # #$`3` #[1] "z" "y" And you can look at the graph using: plot(gg) This is based on an excellent answer...

This will return a set of all detonated cells including the one that started the chain reaction. module Location = type T = {Row: int; Column: int } let subtract l1 l2 = {Row=l1.Row - l2.Row;Column=l1.Column-l2.Colum let detonate (field:Field.T) (start:Cell.T) = let rec inner cells m acc = match cells...

algorithm,graph,graph-algorithm,linear-programming,np-complete

It's possible to formulate this as the following problem. Suppose each vertex v in the graph has weight w(v). You define a variable x(v), and use some out-of-the-box linear programming solver to solve max \sum_v w(v) x(v) (maximize the weight of chosen vertices) subject to x(u) + x(v) <= 1,...

The easiest way is to use Seq.choose s |> Seq.choose id Here we use id as the input is the same as the output...

@bytebuster is making good points of maintainability about custom computation expressions but I still thought I demonstrate how to combine the State and Maybe monad into one. In "traditional" languages we have good support for composing values such as integers but we run into problems when developing parsers (Producing values...

This exact scenario is in the documentation: https://github.com/Readify/Neo4jClient/wiki/cypher-examples#create-a-user

Or you could place a rectangle on the region of interest: rect(xleft=1994,xright = 1998,ybottom=range(CVD$cvd)[1],ytop=range(CVD$cvd)[2], density=10, col = "blue") ...

.net,powershell,f#,system.reactive,f#-async

I ended up creating an EventSink that has a queue of callbacks that are executed on the main PowerShell thread via Drain(). I put the main computation on another thread. The pull request has the full code and more details. ...

algorithm,graph,tree,runtime,big-o

Since everything is still connected and only one edge has been removed, then most (and maybe all) of the spanning tree remains the same. Attempt to construct the same minimum spanning tree, and if the edge that was removed was part of the spanning tree, grab the next smallest edge...

algorithm,graph,graph-algorithm

To get an overall result I'll report what I did. I implemented the in the question mentioned algorithm. (Lets call it thigg's algorithm, because noone mentioned a name) Thigg's algorithm: for each node in the graph: if there is a path from src to this node and a path from...

dictionary,f#,converter,record

In practice, the best advice is probably to use some existing serialization library like FsPickler. However, if you really want to write your own serialization for records, then GetRecordFields (as mentioned in the comments) is the way to go. The following takes a record and creates a map from string...

Your Data value has a type seq<string>, which means that it is lazy. This means that when you perform some computation that accesses it, the lazy sequence will create a new instance of StreamReader and read the data independently of other computations. You can easily see this when you add...

You're right, the line: let ptypedef = ptypedef1 <|> ptypedef2 is the problem. ptypedef1 is consuming some of the input so attempt needs to be used to backtrack when it fails so that ptypedef2 parses the text you're expecting it to, the fixed line would look like: let ptypedef =...

algorithm,graph,graph-algorithm

If you allow preprocessing, there is a fast method: Construct the bridge-block forest, whose vertices are 2-connected components, and whose edges are bridges. (It's a tree if the graph is connected.) When you add an edge, if this connects points in the same 2-connected component, nothing happens. If you connect...