Why colons precede variables in Common Lisp - syntax

What does the syntax, colons preceding variable in Common Lisp, mean? I've seen programs with such, and I'll present some sample code here, out of a large set of functions.
(defun expand (successorf node)
(mapcar (lambda (action-state-cost)
(let ((action (car action-state-cost))
(state (cadr action-state-cost))
(cost (caddr action-state-cost)))
(make-node :state state :parent node
:action action :path-cost (+ (node-path-cost node) cost)
:depth (1+ (node-depth node)))
))
(funcall successorf (node-state node))
))

Keyword Symbols
:foo is a keyword symbol.
interned in and exported from the KEYWORD package
constantly bound to itself
Usage
Keyword symbols are used when one needs the combination of the following properties:
a symbol is the right data structure
symbols with the same name should be unique (by interning them in a package) -> package KEYWORD
different packages are not needed or wanted -> package KEYWORD
writing the symbol should be easy by not needing to quote them -> :foo better than ':foo
the ability to act as a variable with different values is not needed -> :foo evaluates to :foo itself and only to :foo
In Common Lisp generally symbols can be in a package (kind of a namespace).
An unexported symbol bar in a package foo is written as foo::bar. The double colon is between the package name and the symbol name.
An exported symbol then is written as foo:bar. A single colon is used.
If the symbol is available in the current package then is written as bar without the package.
The package KEYWORD
There is a special package called KEYWORD. A symbol bar in that package is simply and always written as :bar.
Examples
These keyword symbols have also these interesting properties: the symbols are automatically exported from the package KEYWORD (so keyword::bar, keyword:bar, ::bar and :bar are all the same symbol) and they evaluate to themselves:
CL-USER 5 > :bar
:BAR
CL-USER 6 > (describe :bar)
:BAR is a SYMBOL
NAME "BAR"
VALUE :BAR
FUNCTION #<unbound function>
PLIST NIL
PACKAGE #<The KEYWORD package, 0/4 internal, 5830/8192 external>
CL-USER 7 > (eq 'keyword::bar ':bar)
T
CL-USER 8 > (eq :bar ':bar) ; quoted or unquoted, each subform evaluates to :bar
T
Usage
Keyword symbols are used for example as names in named arguments:
(defun foo (&key bar) (+ bar 10))
(foo :bar 7)
Typically they are also used in arguments to instance and structure construction.
(defstruct node state parent action)
DEFSTRUCT is a Common Lisp macro and it generates several functions. One of them is a function MAKE-NODE, which can be used as:
(make-node :state 'open
:parent some-parent
:action an-action)
Note: sometimes the data might also be a keyword. For example in above form, the state might be :open and not open:
(make-node :state :open
:parent some-parent
:action an-action)

They're not variables, actually; those are keywords. They're a special kind of efficient token, similar to “atoms” in other languages. It's a convenient, built-in way to pass named (and, almost always, optional) parameters into a function call.
http://www.gigamonkeys.com/book/functions.html describes the syntax of function calls.

Related

key: value vs key :value in ruby?

In associations, we usually do a :b (belongs_to :something). When we create a hash with symbol keys we usually do a: b. Having said that my question is what is the difference between the two syntax. Also is there any logic to memorize when to use which convention?
This isn't about convention, it's about syntax.
:something is a Symbol.
belongs_to :something is a method that is being sent to an implicit self while also omitting the parentheses. We can write it as follows to make that obvious:
self.belongs_to(:something)
:something is thus just an argument being passed to the method belongs_to.
In a Hash, we can use a Symbol as the key:
hash = { :something => "hello" }
Ruby introduced an alternative syntax in version 1.9 that can be used when the key is a symbol:
hash = { something: "hello" }
Both versions are equivalent.
The difference here is between method call and hash key. They look very similar and can easily be confused if you're not sure what you're looking for.
In your first example:
a :b
In long-form this is:
a(:b)
Where now that's clearly an argument (:b) to a method (a).
In the other form it's different:
a: b
Where if that's part of a method call like this:
f a: b
Then that actually means:
f(a: b)
Which in full form is:
f({ a: b })
Where that's a hash definition following the key: value style. Here :a is the key (Symbol) and b is the value (variable or method call).
You'll often see a: :b where you have symbol key and value.
To differentiate between these two forms when reading code have a look at where the code appears to get a sense of context. When writing code, always frame your thinking in terms of method calls and hash definitions more clearly.

Creating record constructors that check for schema in Clojure [duplicate]

I'm learning Clojure and enjoying it but find an inconsistency in Records that puzzles me: why doesn't the default map constructor (map->Whatever) check for data integrity when creating a new Record? For instance:
user=> (defrecord Person [first-name last-name])
#<Class#46ffda99 user.Person>
user=> (map->Person {:first-name "Rich" :last-name "Hickey"})
#user.Person {:first-name "Rich" :last-name "Hickey"}
user=> (map->Person {:first-game "Rich" :last-name "Hickey"})
#user.Person {:first-game "Rich" :first-name nil :last-name "Hickey"}
I believe the Map is not required to define all the fields in the Record definition and it is also allowed to contain extra fields that aren't part of the Record definition. Also I understand that I can define my own constructor which wraps the default constructor and I think a :post condition can then be used to check for correct (and comprehensive) Record creation (have not been successful in getting that to work).
My question is: Is there an idiomatic Clojure way to verify data during Record construction from a Map? And, is there something that I'm missing here about Records?
Thank you.
I think your comprehensiveness requirement is already quite specific, so nothing built-in I know of covers this.
One thing you can do nowadays is use clojure.spec to provide an s/fdef for your constructor function (and then instrument it).
(require '[clojure.spec.alpha :as s]
'[clojure.spec.test.alpha :as stest])
(defrecord Person [first-name last-name])
(s/fdef map->Person
:args (s/cat :map (s/keys :req-un [::first-name ::last-name])))
(stest/instrument `map->Person)
(map->Person {:first-name "Rich", :last-name "Hickey"})
(map->Person {:first-game "Rich", :last-name "Hickey"}) ; now fails
(If specs are defined for ::first-name and ::last-name those will be checked as well.)
Another option is to use Plumatic Schema to create a wrapper "constructor" function specifying the allowed keys. For example:
(def FooBar {(s/required-key :foo) s/Str (s/required-key :bar) s/Keyword})
(s/validate FooBar {:foo "f" :bar :b})
;; {:foo "f" :bar :b}
(s/validate FooBar {:foo :f})
;; RuntimeException: Value does not match schema:
;; {:foo (not (instance? java.lang.String :f)),
;; :bar missing-required-key}
The first line defines a schema that accepts only maps like:
{ :foo "hello" :bar :some-kw }
You wrapper constructor would look something like:
(def NameMap {(s/required-key :first-name) s/Str (s/required-key :last-name) s/Str})
(s/defn safe->person
[name-map :- NameMap]
(map->Person name-map))
or
(s/defn safe->person-2
[name-map]
(assert (= #{:first-name :last-name} (set (keys name-map))))
(map->Person name-map))

Ruby Lisp Interpreter convert arithmetic symbol?

Essentially I have a evaluate method that takes something like
['+','2','3']
which would evaluate to 5.
It's currently set up like so,
def evaluate(exp)
f = exp[0]
if f == '+' then
return exp[1].to_i + exp[2].to_i
elsif f == '-' then
return exp[1].to_i - exp[2].to_i
elsif f == '*' then
return exp[1].to_i * exp[2].to_i
elsif f == '/' then
return exp[1].to_i / exp[2].to_i
end
end
This works fine, but there has to be a better way to do this without a giant if. Is there a way for me to convert the symbol and use it? How do typically lisp interpreters handle this?
Ruby's all about dynamic programming. In fact this makes your code ridiculously easy:
def evaluate(exp)
exp[1].to_i.send(exp[0], exp[2].to_i)
end
It'd be even easier if those tokens were converted on the way in:
exp.map! do |token|
case (token)
when /\A\-?\d+\z/
token.to_i
else
token
end
end
Then you get this:
def evaluate(exp)
exp[1].send(exp[0], exp[2])
end
Now this presumes you're only supplying valid operations, that you're not doing anything absurd, but for trivial cases it works quite well.
If you've converted everything and you're looking to make this more extensible:
def evaluate(exp)
op, *args = exp
args.reduce(&op.to_sym)
end
Then you can do this on arbitrary lists:
evaluate([ '+', 2, 1, 3, 4 ])
def evaluate(*args)
operation, *numbers = args
numbers.map!(&:to_i)
numbers.first.public_send(operation, numbers.last)
end
If you expect more, than two numbers to be used:
def evaluate(*args)
operation, *numbers = args
numbers.map!(&:to_i).inject(&operation.to_sym)
end
evaluate('+','2','3', 4, 5, 6)
#=> 20
You can add an initial value if you need to make sure to always return a Numeric from the method (make sure to select any non-zero number, if operation is division or multiplication):
def evaluate(*args)
operation, *numbers = args
initial_value = %w(/ *).include?(operation) ? 1 : 0
numbers.map!(&:to_i).inject(initial_value, &operation.to_sym) #<==== note 0
end
evaluate '+'
#=> 0
from lisp perspective (common lisp to be precise), you can define evaluate as:
(defun evaluate (func &rest args)
(apply func args))
in first line you define evaluate function to take first argument called func, and rest of them (if any) to put in list called args.
then you apply list of arguments stored in args, to function stored in func.
usage examples:
(evaluate #'print "some text, printed by function evaluated by my own code!")
=> "some text, printed by function evaluated by my own code!"
(evaluate #'+ 2 3)
=> 5
this weird looking #' quotes a function name, otherwise "language" would try to evaluate it as it does with all arguments before passing to function.
i also strongly suggest "structure and interpretation of computer programs", at least videos! in the middle there is this great lecture on evaluation, basically heart of (almost) any computer language on 5 whiteboards! (well... green;)
How do typically lisp interpreters handle this?
Lisp uses symbols for global function names. A symbol is a named thing with a few associated informations. One of these can be a function.
CL-USER 42 > (symbol-function '+)
#<Function + 4100044D34>
CL-USER 43 > (funcall (symbol-function '+) 1 2 3 4)
10
So for your simple expression evaluation:
CL-USER 50 > (defun eval-expression (expression)
(destructuring-bind (function &rest arguments)
expression
(apply function arguments)))
EVAL-EXPRESSION
CL-USER 51 > (eval-expression '(+ 1 2 3 4))
10
Symbols itself are organized in packages, which you can imagine as some kind of specialized table. Packages map names to symbols:
CL-USER 52 > (find-symbol "+")
+
:INHERITED
If you would want to evaluate a string, you first have to read the string to convert the string to Lisp data. The reader will look up the symbols, here +, from the current package:
CL-USER 53 > (eval-expression (read-from-string "(+ 1 2 3 4)"))
10
Since you ask how this is typically done.
You create a lookup table from operations to their implementation. And then use the first element to lookup an implementation and pass the remaining elements to that function.
Essentially all you need to implement a lisp is
evaluate
apply
a lookup table
That kernel might even fit into 30–50 lines. I don't think you want us to give you a complete implementation though. That would take all the fun out of writing your own lisp.
I will thus just outline the basic structure…
$table = {
'+' => lambda { |a, b| a + b },
'-' => lambda { |a, b| a - b },
'*' => lambda { |a, b| a * b },
'/' => lambda { |a, b| a.fdiv(b) },
}
def evaluate(args, context = $table)
# A complete implementation of evaluate would make use of apply ...
head, *tail = args
context[head][*tail]
end
def apply
# ...
end
puts evaluate(['/', 4, 3])
# => 1.3333333333333333
It just so happens that your lisp function names and the corresponding Ruby function names are the same. But that will not always be given, using a lookup table is thus a more typical solution. I mapped the lisp / to Ruby's fdiv to demonstrate that.
Fun fact, these first elements are called symbols and actually Ruby uses a very similar mechanism too and hence also has symbols. Internally, Ruby also uses nested lookup tables to organize classes and constants and methods and local variables, et cetera.
A slightly cleaner version of the same:
def evaluate(operation, *numbers)
numbers.map(&:to_i).reduce(operation)
end
evaluate('+', '2', '3') # => 5
evaluate('/', '6', '2', '3') # => 1
There are many different solutions and you can chose one that more pretty for you, there are a few from me:
exp = ['+','2','3']
def evaluate(exp)
exp.map(&:to_i).inject(exp.shift)
end
# > evaluate(exp)
# => 5
def evaluate(operation, *nums)
nums.map(&:to_i).inject(operation)
end
# > evaluate(*exp)
# => 5

How do you open a file in mit-scheme edwin?

I have a file "file.scm"
(define (foo ...) ...)
(define (bar ...) ...)
(define (baz ...) ...)
If I use (load "file.scm") it returns Value :baz
Since it evaluated baz the function is available to be used, but foo and bar were not evaluated and cannot be used.
What modifications would need to be made to file.scm so that it returns:
Value: foo
Value: bar
Value: baz
when I type (load "file.scm") into the REPL?

Looking for some clarification on Clojure syntax and functionality

What is the difference between this:
(keySet (map (keyword :number) queryResult)
and this:
(keySet (map #(get % "number") queryResult)
First the (keyword :number) from your first example is redundant, because keyword converts its argument to a keyword, and :number is already a keyword. Which reduces your first example to:
(keySet (map :number queryResult))
When a keyword is used as a function, it returns the associated value for that key of the first argument or nil if it doesn't exist:
user=> (:number {:a "Hi" :number 23})
23
user=> (:number {:a "Hi" :ldsf 23})
nil
So the first example returns the result of applying keySet to the sequence of :number fields in queryResult.
Your second example, on the other hand, will apply keySet to the sequence of all "number" fields of queryResult.
Note that the the first example looks up the keyword :number while the second example looks up the string "number".
And of course :number ≠ "number":
user=> (= :number "number")
false
The first one will look up the keyword :number in each item of queryResult, while the second will look up the string "number". Which you want to use will depend on what type the keys in your map are.

Resources