Purely Functional Racket - functional-programming

What are all Racket procedures that mutate state?
I'm trying to create a program with as little side-effects as possible
So, I'd do something like:
#lang racket/base
(provide (except-out (all-from-out racket/base) set! …more here…))
What else should I exclude besides set! ?
Is there a complete list somewhere of all impure functions?
Oh, and the program also uses #lang racket/gui (which is mostly impure, by what I could gather). So that may be tricky...
Thank you.

There is no pre-built list of non-pure functions in Racket.
If you just refrain from using anything which has a ! in the name, you will get close.
Note that you can use mutable data structures and still be programming in a purely functional way - as long as you don't mutate them.

Related

Remove-if-not in Racket

In Common Lisp there is a famous built-in function called remove-if-not.
I could not find this on Racket`s documentation.
Did I miss something? Does Racket offer this function with a different name?
This function is available in Racket under the much more standard name, filter. Its inverse, the equivalent of CL’s remove-if, is available as filter-not.

Replacing an ordinary function with a generic function

I'd like to use names such as elt, nth and mapcar with a new data structure that I am prototyping, but these names designate ordinary functions and so, I think, would need to be redefined as generic functions.
Presumably it's bad form to redefine these names?
Is there a way to tell defgeneric not to generate a program error and to go ahead and replace the function binding?
Is there a good reason for these not being generic functions or is just historic?
What's the considered wisdom and best practice here please?
If you are using SBCL or ABCL, and aren't concerned with ANSI compliance, you could investigate Extensible Sequences:
http://www.sbcl.org/manual/#Extensible-Sequences
http://www.doc.gold.ac.uk/~mas01cr/papers/ilc2007/sequences-20070301.pdf
...you can't redefine functions in the COMMON-LISP package, but you could create a new package and shadow the imports of the functions you want to redefine.
Is there a good reason for these not being generic functions or is just historic?
Common Lisp has some layers of language in some of its areas. Higher-level parts of the software might need to be built on lower-level constructs.
One of its goals was being fast enough for a range of applications.
Common Lisp also introduced the idea of sequences, the abstraction over lists and vectors, at a time, when the language didn't have an object-system. CLOS came several years after the initial Common Lisp design.
Take for example something like equality - for numbers.
Lisp has =:
(= a b)
That's the fastest way to compare numbers. = is also defined only for numbers.
Then there are eql, equal and equalp. Those work for numbers, but also for some other data types.
Now, if you need more speed, you can declare the types and tell the compiler to generate faster code:
(locally
(declare (fixnum a b)
(optimize (speed 3) (safety 0)))
(= a b))
So, why is = not a CLOS generic function?
a) it was introduced when CLOS did not exist
but equally important:
b) in Common Lisp it wasn't known (and it still isn't) how to make a CLOS generic function = as fast as a non-generic function for typical usage scenarios - while preserving dynamic typing and extensibility
CLOS generic function simply have a speed penalty. The runtime dispatch costs.
CLOS is best used for higher level code, which then really benefits from features like extensibility, multi-dispatch, inheritance/combinations. Generic functions should be used for defined generic behavior - not as collections of similar methods.
With better implementation technology, implementation-specific language enhancements, etc. it might be possible to increase the range of code which can be written in a performant way using CLOS. This has been tried with programming languages like Dylan and Julia.
Presumably it's bad form to redefine these names?
Common Lisp implementations don't let you replace them just so. Be aware, that your replacement functions should be implemented in a way which works consistently with the old functions. Also, old versions could be inlined in some way and not be replaceable everywhere.
Is there a way to tell defgeneric not to generate a program error and to go ahead and replace the function binding?
You would need to make sure that the replacement is working while replacing it. The code replacing functions, might use those function you are replacing.
Still, implementations allow you to replace CL functions - but this is implementation specific. For example LispWorks provides the variables lispworks:*packages-for-warn-on-redefinition* and lispworks:*handle-warn-on-redefinition*. One can bind them or change them globally.
What's the considered wisdom and best practice here please?
There are two approaches:
use implementation specific ways to replace standard Common Lisp functions
This can be dangerous. Plus you need to support it for all implementations of CL you want to use...
use a language package, where you define your new language. Here this would be standard Common Lisp plus your extensions/changes. Export everything the user would use. In your software use this package instead of CL.

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.

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.

Learning Scheme Macros. Help me write a define-syntax-rule

I am new to Scheme Macros. If I just have one pattern and I want to combine the define-syntax and syntax-rules, how do I do that?
(define-syntax for
(syntax-rules (from to)
[(for i from x to y step body) ...]
[(for i from x to y body) ...]))
If I just have one for, how do I combine the syntax definition and the rule?
Thanks.
In other words, you decided that for really only needs one pattern and want to write something like:
(defmacro (for ,i from ,x to ,y step ,body)
; code goes here
)
There is nothing built-in to Scheme that makes single-pattern macros faster to write. The traditional solution is (surprise!) to write another macro.
I have used defsubst from Swindle, and PLT Scheme now ships with define-syntax-rule which does the same thing. If you are learning macros, then writing your own define-syntax-rule equivalent would be a good exercise, particularly if you want some way to indicate keywords like "for" and "from". Neither defsubst nor define-syntax-rule handle those.

Resources