Suppose I am solving a problem (e.g. N-Queen) with backtracking. What if I want to find the only one (the 1-st) solution rather than all of them.
I guess I can do it imperatively (e.g. with a mutable boolean flag). I wonder how I can do it functionally.
While Scala's Option will work here, as two other answers have pointed out, a more idiomatic functional approach would be to use a "lazy list"—or a Stream, in Scala—to represent the set of solutions.
I've found myself writing code like this, for example:
trait Node[A] {
def children: Stream[A with Node[A]]
def dfs(f: A => Boolean): Stream[A] = this.children.flatMap {
child => if (f(child)) Stream(child) else child.dfs(f)
}
}
Now suppose I have a Board class that extends Node[Board] and that has an implementation of the children method that returns all valid boards with one additional piece. Suppose it also has some other useful stuff, like a size method, a companion object with an empty, etc.
I can then write the following to get a Stream of solutions:
val solutions = Board.empty.dfs(_.size == 8)
A Stream is lazy and only evaluates its head, so right now we've only searched the tree far enough to find the first solution. We can get this solution using head:
scala> solutions.head
res1: Board =
o . . . . . . .
. . . . o . . .
. . . . . . . o
. . . . . o . .
. . o . . . . .
. . . . . . o .
. o . . . . . .
. . . o . . . .
Or whatever. But I can also get other results if I want them:
scala> solutions(10)
res2: Board =
. o . . . . . .
. . . . . . o .
. . . . o . . .
. . . . . . . o
o . . . . . . .
. . . o . . . .
. . . . . o . .
. . o . . . . .
This searches just enough more of the tree to find the tenth solution, and then stops.
The big advantage of Stream over the Option approach is that I can get additional results if I need them, without paying more for the first.
Here's a simple case with a depth-first search that stops when it finds what it's looking for. It makes use of Option, as mentioned in Chris K's answer.
case class Tree[A](v: A, subtrees: Tree[A]*) {
def dfs(s: A): Option[A] = {
println("visiting " + v)
subtrees.foldLeft(if(v == s) Some(v) else None)((r, t) =>
if(r.isDefined)
r
else
t.dfs(s)
)
}
override def toString() = "Tree(%s%s%s)".format(v, if(subtrees.nonEmpty) ", " else "", subtrees.mkString(", "))
}
Usage:
scala> val t = Tree(1, Tree(2, Tree(3), Tree(4)), Tree(5, Tree(6), Tree(7)))
t: Tree[Int] = Tree(1, Tree(2, Tree(3), Tree(4)), Tree(5, Tree(6), Tree(7)))
The tree t looks like
1
/ \
2 5
/ \ / \
3 4 6 7
So we can search for an element and trace the nodes it visits:
scala> t.dfs(6)
visiting 1
visiting 2
visiting 3
visiting 4
visiting 5
visiting 6
res42: Option[Int] = Some(6)
Notice that we don't visit any more nodes after we find what we're looking for.
Assuming you're using a recursive search function, your function should either return a result (i.e. positioning of the queens) or an indication that no result could be found for that branch. Scala probably has an option/maybe type, you can use that. This advice is equally applicable to any functional language.
Related
I am using prettify-symbols to switch between the following words and shortcuts. The problem is that when the replacement is more than a single character, all letters are being inserted at the same point.
For instance when little is replaced I get a single l, rather than ll.
(defvar cluster
'(
("all" . "l") ("as" . "as") ("can" . "k")
("do" . "do") ("for" . "f") ("in" . "n")
("is" . "s") ("it" . "t") ("know" . "no")
("like" . "lk") ("little" . "ll") ("more" . "mo")
("some" . "so") ("than" . "n") ("that" . "ta")
("there" . "tr") ("this" . "th") ("time" . "ti")
("to" . "to") ("we" . "w") ("well" . "l")
("will" . "l") ("work" . "wk") ("you" . "u"))
"List of replacements for specific words.")
(defun prettify-cluster ()
"Set keywords and corresponding glyph."
(setq-local prettify-symbols-alist cluster))
The doc string of variable prettify-symbols-alist tells you that each alist entry is (SYMBOL . CHARACTER), where SYMBOL is a string.
In your alist, you have instead (STRING . STRING) entries.
prettify-symbols-alist is a variable defined in prog-mode.el.
Its value is nil
Automatically becomes buffer-local when set.
Documentation:
Alist of symbol prettifications.
Each element looks like (SYMBOL . CHARACTER), where the symbol
matching SYMBOL (a string, not a regexp) will be shown as
CHARACTER instead.
CHARACTER can be a character, or it can be a list or vector, in
which case it will be used to compose the new symbol as per the
third argument of compose-region.
Furthermore, if you use a list or vector of chars for CHARACTER then those chars are composed.
I think that what you want is maybe something like abbrev-mode?
My team is implementing a variation of Ceusters's Referent Tracking. In our implementation, the original URI for an entity can be changed (to something containing a UUID), although a link to the original URI is always kept.
For example:
:Joey rdf:type :person .
:New_York_City rdf:type :locality .
:Joey :hometown :New_York_City .
might become:
:Joey :replacedWith :ABC123 .
:ABC123 rdf:type :person .
:New_York_City :replacedWith :FFF555 .
:FFF555 rdf:type :locality .
:ABC123 :hometown :FFF555 .
I am writing some Scala integration tests to see if our software does the referent tracking correctly.
Specifically, I know I should expect this CorrectPattern:
:Joey :replacedWith ?person .
?person rdf:type :person .
:New_York_City :replacedWith ?locale .
?locale rdf:type :locality .
?person :hometown ?locale .
But I don't know what the values of ?person and ?locale will be.
I can SPARQL ASK for CorrectPattern... that will tell me if the pattern is present. But I also want to confirm that nothing else has been added.
I thought I could CONSTRUCT { ?s ?p ?o }, MINUS out CorrectPattern, and check for an empty result, but Blazegraph is saying:
java.util.concurrent.ExecutionException: org.openrdf.query.MalformedQueryException: CONSTRUCT WHERE only permits statement patterns in the WHERE clause.
Any ideas? I want to check that the whole triple store contains nothing more and nothing less than CorrectPattern, but I think CorrectPattern must contain variables.
Once again bailed out by a comment from #AKSW, who doesn't seem to be especially obsessed with earning reputation points.
This CONSTRUCT, with an embedded SELECT, gets all triples from my model, depleted of any triples in the MINUS block, even when they contain variables. I'm pretty sure I can flesh out the MINUS block and finish my task.
PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>
CONSTRUCT
{
?s ?p ?o .
}
WHERE
{ SELECT ?s ?p ?o
WHERE
{ { ?s ?p ?o }
MINUS
{ ?s rdf:type ?o }
}
}
In order to determine that the triple-store contains only the triples which you expect and nothing more, you could test for the exact triples which you expect while simultaneously counting the number of triples which appear in the database before and after you run your program. If the difference in triples is higher or lower than you expect, you will know that you have some extraneous or missing data.
Use SPARQL SELECT Count function:
SELECT (count(?triples) as ?count)
WHERE {
?triples ?p ?o .}
Pseudocode:
val beforeTripleCount = countTriplesInDatabase()
//run your program, test for expected triples
val afterTripleCount = countTriplesInDatabase()
val diff = afterTripleCount - beforeTripleCount
//diff should be equal to the number of triples you expect to be added/removed
Additionally, if you are resistant to using variables in your tests, you could write additional queries to capture the URI of the node you have created, then add the results to your test queries using String concatenation.
I have a text file with a long list of variables like this:
a VARCHAR(32),
b INT,
c TINYINT,
.
.
.
I want to quickly swap the order of the name and type so I have:
VARCHAR(32) a,
INT b,
TINYINT c
.
.
.
Im happy to use a bash terminal or notepad ++ and I do have a basic knowledge of regex but Im not sure how to tackle this problem.
How can I go about doing this?
you can use this app I just wrote:
http://codepen.io/franzskuffka/pen/Ndxejz
Or run it through this function
function swap (text) {
let lines = text.split(',\n')
let parts = lines.map(function (line) {
var lineParts = line.split(' ')
lineParts[2] = lineParts[0]
delete lineParts[0]
return lineParts.join(' ')
})
return parts.join(',\n')
}
Generally I recommend the text editor Kakoune for this task which is awesome for text processing in general due to the multicursor support and incremental editing.
So I'm trying to access a hash table in Racket, but I can not figure out why it's not working.
When I call hash->list on this hash:
{"26220765": [
{
"queue": "RANKED_SOLO_5x5",
"name": "Viktor's Marauders",
"participantId": "26220765",
"entries": [
{
"leaguePoints": 0,
"isFreshBlood": false,
"isHotStreak": false,
"division": "IV",
"isInactive": false,
"isVeteran": true,
"losses": 168,
"playerOrTeamName": "iGT500",
"playerOrTeamId": "32156611",
"wins": 173
},
{
"leaguePoints": 0,
"isFreshBlood": true,
"isHotStreak": false,
"division": "V",
"isInactive": false,
"isVeteran": false,
"losses": 255,
"playerOrTeamName": "dragdan",
"playerOrTeamId": "20430418",
"wins": 265
},
It returns
((|26220765| #hasheq((name . "Viktor's Marauders") (queue . "RANKED_SOLO_5x5") (tier . "PLATINUM") (entries . (#hasheq((playerOrTeamId . "32156611") (division . "IV") (playerOrTeamName . "iGT500") (leaguePoints . 0) (wins . 173) (losses . 168) (isHotStreak . #f) (isVeteran . #t) (isFreshBlood . #f) (isInactive . #f)) #hasheq((playerOrTeamId . "20430418") (division . "V") (playerOrTeamName . "dragdan") (leaguePoints . 0) (wins . 265) (losses . 255) (isHotStreak . #f) (isVeteran . #f)
I can not access the hash by using the key 26220765. I've tried defining it as summoner-id and passing it, i've tried using '26220765, it doesn't work. I don't understand why it's being displayed with vertical bars, and if I try '|26220765| or |26220765| it doesn't work either.
I had another hash table where I needed to access the hash "champions", and using 'champions worked, so why isn't this working?
This works:
#lang racket/base
(require json)
(define js (string->jsexpr "{\"123\": \"val\"}"))
js ;=> '#hasheq((|123| . "val"))
(hash-ref js '|123|) ;=> "val"
Do you have a similarly short example of what doesn't work for you?
p.s. You may find people more motivated to answer, if you take a moment to accept and/or upvote answers. Like Racket string to literal? and Getting a specific hash-table from a list in racket?.
In Racket there are different constructors for hash tables. The difference between them is that the hash table uses different comparators (eq? , equal? , eqv?, ...).
That's probably the reason why it doesn't work always like you would want it to.
The different hash tables in racket
In fact when making a hash table it has to know which comparator to use to check for equality. You could for example imagine a generic implementation where you have to pass your own lambda to be used as comparator.
I'm using libconfuse for my program's configuration files, and that's working nicely. Now I'm interested to parse the configuration files using Augeas. I found a mailing list post which says that there's no generic Augeas lens for libconfuse files, because it's a "context-free file format" (in essence, it allows infinite nesting).
My program's configuration files are quite simple, with just one level of sections containing configuration parameters. E.g.:
serial {
serial-device = "/dev/ttyUSB0"
baudrate = 115200
}
server-socket {
host = "localhost"
port = 12345
}
What would be involved in writing a generic Augeas lens for this simple variety of libconfuse configuration file? Are there any examples around? What would be the most straight-forward way to handle this?
The post you're referring to is from 2008. Augeas has since been able to parse recursive configuration files, using the rec keyword. See for example lvm.aug, which is quite similar to what you're trying to achieve.
Thanks to ℝaphink's answer, I started with the lvm.aug lens, which was a good starting point, and improved it a little.
Here's what I've got at the moment, which supports only a subset of libconfuse syntax—if you test it with the libconfuse example test.conf, it will fail in several places. But it works for the sub-set of the syntax in the config files I'm currently using, so it's "good enough" for my current purposes. Although I'd like to figure out how to get indentation of nested blocks looking nice (like the json.aug lens does; I haven't figured out how it does it yet).
(*
Module: LibconfuseSimple
Based on Module LVM
*)
module LibconfuseSimple =
(* See lvm2/libdm/libdm-config.c for tokenisation;
* libdm uses a blacklist but I prefer the safer whitelist approach. *)
(* View: identifier
* The left hand side of a definition *)
let identifier = /[a-zA-Z0-9_-]+/
(* strings can contain backslash-escaped dquotes, but I don't know
* how to get the message across to augeas *)
let str = [label "str". Quote.do_quote (store /[^"]*/)]
let int = [label "int". store Rx.integer]
let env = [label "env". del "${" "${" . store /[^}]*/ . del "}" "}"]
let const (r:regexp) = [ label "const" . store r ]
let rawstr = [label "rawstr". store Rx.space_in]
(* View: flat_literal
* A literal without structure *)
let flat_literal = int|str|env|const /true|false|null/|rawstr
(* allow multiline and mixed int/str, used for raids and stripes *)
(* View: list
* A list containing flat literals *)
let list = [
label "list" . counter "list"
. del /\[[ \t\n]*/ "["
.([seq "list". flat_literal . del /,[ \t\n]*/ ", "]*
. [seq "list". flat_literal . del /[ \t\n]*/ ""])?
. Util.del_str "]"]
(* View: val
* Any value that appears on the right hand side of an assignment *)
let val = flat_literal | list
(* View: comments
* Comments of various sorts *)
let comments =
Util.comment
| Util.comment_c_style
| Util.comment_multiline
(* View: nondef
* A line that doesn't contain a statement *)
let nondef =
Util.empty
| comments
(* View: indent
* Remove any input indentation; output 4 spaces indentation. *)
let indent = del /[ \t]*/ " "
(* Build.block couldn't be reused, because of recursion and
* a different philosophy of whitespace handling. *)
(* View: def
* An assignment, or a block containing definitions *)
let rec def = [
key identifier . (
(del /[ \t]*/ " " . [label "title" . store identifier])? . del /[ \t]*\{\n?/ " {\n"
.[label "dict" . (Util.empty | indent . comments | indent . def)*]
. Util.indent . Util.del_str "}\n"
|Sep.space_equal . val . Util.comment_or_eol)]
(* View: lns
* The main lens *)
let lns = (nondef | (Util.indent . def))*