Make Complex arithmetic the default within a Clojure project - math

you've been spectacularly helpful to me so far, I hope you can help me get my mind around this one. I am building a project that does computations with complex matrices. I have been using mikera/core.matrix.complex, which uses mikera/core.matrix for matrix stuff, and complex.core for defining complex numbers in clojure.
I want to be able to do any and all arithmetic, including using irrational numbers like e (def e (Math/E)) and pi (def pi (Math/PI)), and including matrix math that may or may not be complex. The problem comes when I mix functions from different libraries.
Right now my namespace looks like this:
(ns qgame.utils.math
(:require
[clojure.walk :as w :refer [postwalk
prewalk]]
[clojure.core.matrix :as mat]
[clojure.core.matrix.complex :as compl]
[incanter.core :as ic]
[complex.core :as c :refer [+ - / *]]))
If I do (mat/mmul matrix1 matrix2), then everything is treated as a regular number, and using complex numbers messes it up. I get a lot of ClassCastException org.apache.commons.math3.complex.Complex cannot be cast to java.lang.Number. If I just require core.matrix.complex without requiring core.matrix, then none of the matrix functions work.
The same goes for stuff like (+ 3 4). If I directly (use 'complex.core) in a repl, then that will evaluate to (7.0, 0.0), which is what I want, otherwise it just comes out as 7.
I feel like I'm making this more complicated than it is, the core.matrix.complex looks like it has extensions for everything in core.matrix and clojure.core, but it doesn't utilize it with the namespace declaration that I have. I'm not that familiar with Clojure protocols, so there is definitely something that I am missing. I just want all three libraries to be included, and to have any and all math be done in the context of complex numbers, i.e 1 = (1.0, 0.0), and (Math/exp (* pi (complex 0 1)) => (-1.0, 0.0)
How can I go about doing this? Sorry if I'm not being clear, I'll try and clear up any questions people have about what I'm asking.
Edit: I've been thinking about the problem, and really the best place to start is the last equation that I listed: Getting e^pi*i to equal -1. If I try to use Math/exp with complex numbers, I get a casting exception.

I'm not familiar with core.matrix.complex but here are some points you are probably not aware of. This is technically not an answer but it's too long to fix in a comment.
core.matrix defined a set of API, in the form of protocols, defined here.
core.matrix.complex does not extend all protocols to complex matrices. For example, the mat/mmul defined here relies on the protocol PMatrixMultiply. But this protocol is not extended to complex matrices.
(+ 3 4) returns (7.0, 0.0) after use-ing complex.core because complex.core rewrote the function/operator +. But I doubt whether you should refer these operators. complex.core is merely a thin wrapper around org.apache.commons.math3.complex.Complex and it knows nothing about matrices. Perhaps you'll be better off using functions/operators in core.matrix API like add.

Related

How do I get turnstile to work in isabelle?

I was wondering how do I get turnstile to work in Isabelle 2017. I new to the program and have been able to work some thereoms but I can't figure out how to get the turnstile symbol to work. Do I have change imports or is there something else I have to do?
Thanks.
Okay, so it seems like you want to define some custom syntax involving the turnstile symbol.
This is described in Sections 8.2 and 8.3 of the Isabelle/Isar reference manual (and some more advanced stuff in Sections 8.5.2 and 8.5.3). You can do a lot of fancy custom syntax with Isabelle: the list syntax [1, 2, 3] for Cons 1 (Cons 2 (Cons 3 Nil)), for example, is defined entirely in ‘user space’, as is the list comprehension syntax [x + y. x ← xs, y ← ys, x ≠ y]. These are pretty complicated.
However, in most cases, you only need a very small fragment of all that power: As outline in Section 8.2 of isar-ref, you can annotate syntax directly to constants as you define them (e.g. with definition, primrec, fun, datatype) by either using something like infixl, infixr, or binder, or by directly providing a mixfix syntax specification. The tricky part here is often defining the precedences so that they don't clash with other stuff.
If you get this wrong, you will get warnings (not upon defining the syntax, but upon using it) telling you that there are ambiguous parse trees and that you should perhaps try to disambiguate your syntax by providing better mixfix priorities.
For examples of how this looks in practice you can look, well, basically at any Isabelle syntax you already know by going to where it is defined and looking at the mixfix specification.
One place that comes to my mind is the ~~/src/HOL/IMP directory, in particular the files Hoare.thy and Types.thy. They define some custom syntax, some of which even includes the turnstile symbol.

Recursively run through a vector in Clojure

I'm just starting to play with Clojure.
How do I run through a vector of items?
My naive recursive function would have a form like the classic map eg.
(defn map [f xs] (
(if (= xs [])
[]
(cons (f (first xs)) (map f (rest xs))
)
))
The thing is I can't find any examples of this kind of code on the web. I find a lot of examples using built-in sequence traversing functions like for, map and loop. But no-one doing the raw recursive version.
Is that because you SHOULDN'T do this kind of thing in Clojure? (eg. because it uses lower-level Java primitives that don't have tail-call optimisation or something?)?
When you say "run through a vector" this is quite vague; as Clojure is a lisp and thus specializes in sequence analysis and manipulation, the beauty of using this language is that you don't think in terms "run through a vector and then do something with each element," instead you'd more idiomatically say "pull this out of a vector" or "transform this vector into X" or "I want this vector to give me X".
It is because of this type of perspective in lisp languages that you will see so many examples and production code that doesn't just loop/recur through a vector but rather specifically goes after what is wanted in a short, idiomatic way. Using simple functions like reduce map filter for into and others allow you to elegantly move over a sequence such as a vector while simultaneously doing what you want with the contents. In most other languages, this would be at least 2 different parts: the loop, and then the actual logic to do what you want.
You'll often find that if you think about sequences using the more imperative idea you get with languages like C, C++, Java, etc, that your code is about 4x longer (at least) than it would otherwise be if you first thought about your plan in a more functional approach.
Clojure re-uses stack frames only with tail-recurstion and only when you use the explicit recur call. Everything else will be stack consuming. The above map example is not tail recursive because the cons happens after the recursive call so it can't be TCO'd in any language. If you switch it to use the continuation passing style and use an explicit call to recur instead of map then you should be good to go.

Fixed-Point Combinators

I am new to the world of fixed-point combinators and I guess they are used to recurse on anonymous lambdas, but I haven't really got to use them, or even been able to wrap my head around them completely.
I have seen the example in Javascript for a Y-combinator but haven't been able to successfully run it.
The question here is, can some one give an intuitive answer to:
What are Fixed-point combinators, (not just theoretically, but in context of some example, to reveal what exactly is the fixed-point in that context)?
What are the other kinds of fixed-point combinators, apart from the Y-combinator?
Bonus Points: If the example is not just in one language, preferably in Clojure as well.
UPDATE:
I have been able to find a simple example in Clojure, but still find it difficult to understand the Y-Combinator itself:
(defn Y [r]
((fn [f] (f f))
(fn [f]
(r (fn [x] ((f f) x))))))
Though the example is concise, I find it difficult to understand what is happening within the function. Any help provided would be useful.
Suppose you wanted to write the factorial function. Normally, you would write it as something like
function fact(n) = if n=0 then 1 else n * fact(n-1)
But that uses explicit recursion. If you wanted to use the Y-combinator instead, you could first abstract fact as something like
function factMaker(myFact) = lamba n. if n=0 then 1 else n * myFact(n-1)
This takes an argument (myFact) which it calls were the "true" fact would have called itself. I call this style of function "Y-ready", meaning it's ready to be fed to the Y-combinator.
The Y-combinator uses factMaker to build something equivalent to the "true" fact.
newFact = Y(factMaker)
Why bother? Two reasons. The first is theoretical: we don't really need recursion if we can "simulate" it using the Y-combinator.
The second is more pragmatic. Sometimes we want to wrap each function call with some extra code to do logging or profiling or memoization or a host of other things. If we try to do this to the "true" fact, the extra code will only be called for the original call to fact, not all the recursive calls. But if we want to do this for every call, including all the recursive call, we can do something like
loggingFact = LoggingY(factMaker)
where LoggingY is a modified version of the Y combinator that introduces logging. Notice that we did not need to change factMaker at all!
All this is more motivation why the Y-combinator matters than a detailed explanation from how that particular implementation of Y works (because there are many different ways to implement Y).
To answer your second question about fix-point combinators other than Y. There are countably infinitely many standard fix-point combinators, that is, combinators fix that satisfy the equation
fix f = f (fix f)
There are also contably many non-standard fix-point combinators, which satisfy the equation
fix f = f (f (fix f))
etc. Standard fix-point combinators are recursively enumerable, but non-standard are not. Please see the following web page for examples, references and discussion.
http://okmij.org/ftp/Computation/fixed-point-combinators.html#many-fixes

What is define-struct in Racket and why are there no variables?

In one of my CS courses at university we have to work with Racket. Most of my programming time before university I spent with PHP and Java and also JavaScript. I know Racket is a functional programming language, just like JavaScript (Edit: Of course it isn't. But I felt like I was doing 'functional' programming with it, which after seeing the answers, is a wrong perception.) But I still don't understand some fundamental characteristics of Racket (Scheme).
Why are there no 'real' variables? Why is everything a function in Racket/Scheme? Why did the language designers not include them?
What is define-struct? Is it a function? Is it a class? I somehow, because of my PHP background, always think it's a class, but that can't be really correct.
My question here is I want to understand the concept of the language. I personally still think it's really strange and not like anything I worked with before, so my brain tries to compare it with JavaScript, but it just seems so different to me. Parallels/differences to JavaScript would help a lot!
There are 'real' variables in Racket. For example, if you write this
code
(define x 3)
the 'global' variable x will be set to value 3. If you now write
(set! x 4)
the variable x will change its value to 4. So, in Racket you can
have a 'normal' variables like in any 'normal' language, if you
want. The fact is that in Racket the preferred programming style is
functional as opposed to procedural. In functional programming style
variable mutation is discouraged.
define-struct is a Racket macro that you use to define 'structure
template' along with several other things. For example, if you
write:
(define-struct coord (x y))
you just defined a 'structure template' (i.e user type named coord
that have two "slots": x and y). After that, you can now:
create new "instance" of structure coord, for example like this:
(make-coord 2 3)
extract slot value from the structure object:
(coord-x (make-coord 2 3)) ;will return 2
or
(coord-y (make-coord 2 3)) ;will return 3
you can ask if some given object is just that structure. For
example, (coord? 3) will return #f, since 3 is not of type coord
structure, but
(coord? (make-coord 2 3)) ;will return #t
Perhaps the most popular or in-fashion way to program (using languages like C++, Javascript, and Java) has a few characteristics. You may take them for granted as self-evident, the only possible way. They include:
Imperative
You focus on saying "do this step, then this next step" and so on.
Using mutation.
You declare a variable, and keep assigning it different values ("mutate it").
Object-oriented.
You bundle code and data into classes, and declare instances of them as objects. Then you mutate the objects.
Learning Scheme or Racket will help you understand that these aren't the only way to go about it.
It might make your brain hurt at first, in the same way that a philosophy class might cause you to question things you took for granted. However unlike the philosophy class, there will be some practical pay-off to making brain hurt. :)
An alternative:
Functional (instead of imperative). Focus on expressions that return values, instead of making to-do lists of steps.
Immutable. Ditto.
Not object oriented. Using objects of classes can be a good approach to some problems, but not all. If you want to bundle code with data, there are some more general ways to go about it, such as closures with "let over lambda" and so on. Sometimes you don't need all the "baggage" of classes and especially inheritance.
Scheme and Racket make it easy to explore these ideas. But they are not "pure functional" like say Haskell, so if you really want to do imperative, mutable, object-oriented things you can do that, too. However there's not much point in learning Racket to do things the same way you would in Javascript.
Scheme very much has "real" variables.
The difference between a functional language (like Racket) and an imperative language (like JavaScript or PHP) is that in a functional language, you usually don't use mutable state. Variables are better thought of as names for values than as containers that can hold values. Instead of using things like looping constructs to change values in variables, you instead use recursion for flow control.
define-struct is a special syntactic form, kind of like keywords in other languages. (Unlike other languages, in Scheme you can create your own syntactic forms.) It defines a struct type, which is like a class but doesn't have methods. It also defines a number of functions that help you utilize your new struct type.
There are variables in Scheme.
> (define a 1)
#<unspecified>
> a
1
> (set! a 2)
#<unspecified>
> a
2
There are even mutable data structures in this language.
> (begin
> (define v (make-vector 4))
> (vector-set! v 0 'foo)
> (vector-set! v 1 'bar)
> (vector-set! v 2 'baz)
> (vector-set! v 3 'quux))
#<unspecified>
> v
#(foo bar baz quux)
Scheme is not a pure FP language; it does allow imperative programming, although it is mostly geared towards functional programming. That's a design choice that Scheme's inventors made.
define-struct is a special form; it's syntax, like the function or return keywords in JavaScript.

Mapping over sequence with a constant

If I need to provide a constant value to a function which I am mapping to the items of a sequence, is there a better way than what I'm doing at present:
(map my-function my-sequence (cycle [my-constant-value]))
where my-constant-value is a constant in the sense that it's going to be the same for the mappings over my-sequence, although it may be itself a result of some function further out. I get the feeling that later I'll look at what I'm asking here and think it's a silly question because if I structured my code differently it wouldn't be a problem, but well there it is!
In your case I would use an anonymous function:
(map #(my-function % my-constant-value) my-sequence)
Using a partially applied function is another option, but it doesn't make much sense in this particular scenario:
(map (partial my-function my-constant-value) my-sequence)
You would (maybe?) need to redefine my-function to take the constant value as the first argument, and you don't have any need to accept a variable number of arguments so using partial doesn't buy you anything.
I'd tend to use partial or an anonymous function as dbyrne suggests, but another tool to be aware of is repeat, which returns an infinite sequence of whatever value you want:
(map + (range 4) (repeat 10))
=> (10 11 12 13)
Yet another way that I find sometimes more readable than map is the for list comprehension macro:
(for [x my-sequence]
(my-function x my-constant-value))
yep :) a little gem from the "other useful functions" section of the api constantly
(map my-function my-sequence (constantly my-constant-value))
the pattern of (map compines-data something-new a-constant) is rather common in idomatic clojure. its relativly fast also with chunked sequences and such.
EDIT: this answer is wrong, but constantly and the rest of the "other useful functions" api are so cool i would like to leave the reference here to them anyway.

Resources