"for each" or "every" keywords in Scheme - loops

Is there a for loop or for each loop in Scheme ?
I've been searching around and found there is a keyword "every" but the scheme compiler language I'm using does not have this function pre-build in. This is what it suppose to do, it can be find here
(define (first-letters sent)
(every first sent))
> (first-letters '(here comes the sun))
(H C T S)
How can I re-write the every function ? using other pre-defined function. The language I'm using is in the DrScheme - Essentials of Programming Languages (3rd ed)
I tried all the pre-installed compiler in DrScheme none of them can compile the every function.
Any ideas ?

You are looking for map, although you probably would like to know that Scheme also has for-each. map does exactly what you want with every. It does something to each item in the list, returning a new list of the results.
You could even say
(define every map)
You can get your first function by writing
(define (first symbol)
(string->symbol (string (string-ref (symbol->string symbol) 0))))
This is bad Scheme style, though. It looks like ancient Lisp from the 60s or 70s, back before strings were in the language.
Anyway, Now you can say
(map first '(here comes everybody))
=> (h c e)
for-each does some kind of side effect to each item in the list:
(define initials (map first '(here comes everybody)))
(for-each display initials)
=> hce

This could be the answer of your question. Map function, takes a function and list(-s) as arguments, applies function to elements of list, returns the results.

This is an addition to Nathan's post, which is the best answer for you right now...
If you ever move over to the scheme or scheme/base module languages, you will gain access to PLT's army of for iterators. These look a bit more like the "for each" loops that are common in other languages. Search for for in the docs:
(define (first symbol)
(string->symbol (string (string-ref (symbol->string symbol) 0))))
(for/list ([symbol (in-list '(here comes everybody))])
(first symbol))
=> '(h c e)

Depends which Scheme you're looking at. Apart from "for-each" and "map" mentioned above (which are part of the various standards, hence present in all real Schemes), you can find impelementation-specific extensions. For example, PLT scheme has a whole slew of such forms, which you can read about here.

Related

Racket: Macro outputs something weird instead of an array

My aim is to populate an array in compile phase (i.e. in a macro), and use it in execution phase. For some reason, though, object returned by a macro is not recognized by Racket as an array. To illustrate the problem, shortest code showing this behaviour:
(require (for-syntax math/array))
(require math/array)
(define-syntax (A stx)
(datum->syntax stx `(define a ,(array #[#[1 2] #[3 4]]))))
(A)
After execution of this macro, 'a' is something, but I don't know what it is. It is not an array ((array? a) -> #f) nor a string, array-ref is not working on it, obviously, but it prints as: (array #[#[1 2] #[3 4]]). "class-of" from the "swindle" module claims it is "primitive-class:unknown-primitive", for what it's worth.
I have tried outputting a vector instead of an array, but it works as expected, i.e. resulting value is a vector in execution phase.
I have tried using CommonLisp style defmacro from "compatibility" module, thinking that this may have something to do do with datum->syntax transformation, but this changed nothing.
I have tested this on Win7 with Racket 6.5 and 6.7, as well as on Linux with Racket 6.7 - problem persists.
Any ideas?
update
Thanks to great answers and suggestions, I came up with following solution:
(require (for-syntax math/array))
(require math/array)
(define-syntax (my-array stx)
(syntax-case stx ()
[(_ id)
(let
([arr (build-array
#(20 20)
(lambda (ind)
(let
([x (vector-ref ind 1)]
[y (vector-ref ind 0)])
(list 'some-symbol x y (* x y)))))])
(with-syntax ([syn-arr (eval (read (open-input-string (string-append "#'" (format "~v" arr)))))])
#'(define id syn-arr)))]))
(my-array A)
I'm not sure if this is proper Racket (I welcome all suggestions on code improvement) but here is how it works:
Array is built and stored in "arr" variable. It is then printed to string, prepended with #' (so that this string represents syntax object now) and evaluated as code. This effectively converts array to syntax object, that can be embedded in macro output.
Advantage of this approach is, that every object that can be written out and then read back by Racket can be output by macro. Disadvantage is, that some objects can't (I'm looking at you, custom struct!) and therefore additional string-creating function may be required in some cases.
First of all, don’t use datum->syntax like that. You’re throwing away all hygiene information there, so if someone was using a different language where define was called something else (like def, for example), that would not work. For a principled introduction to Racket macros, consider reading Fear of Macros.
Second of all, the issue here is that you are creating what is sometimes known as “3D syntax”. 3D syntax should probably be an error in this context, but the gist is that there is only a small set of things that you can safely put inside of a syntax object:
a symbol
a number
a boolean
a character
a string
the empty list
a pair of two pieces of valid syntax
a vector of valid syntax
a box of valid syntax
a hash table of valid syntax keys and values
a prefab struct containing exclusively valid syntax
Anything else is “3D syntax”, which is illegal as the output of a macro. Notably, arrays from math/array are not permitted.
This seems like a rather extreme limitation, but the point is that the above list is simply the list of things that can end up in compiled code. Racket does not know how to serialize arbitrary things to bytecode, which is reasonable: it wouldn’t make much sense to embed a closure in compiled code, for example. However, it’s perfectly reasonable to produce an expression that creates an array, which is what you should do here.
Writing your macro more properly, you would get something like this:
#lang racket
(require math/array)
(define-syntax (define-simple-array stx)
(syntax-case stx ()
[(_ id)
#'(define id (array #(#(1 2) #(3 4))))]))
(define-simple-array x)
Now, x is (array #[#[1 2] #[3 4]]). Note that you can remove the for-syntax import of math/array, since you are no longer using it at compile time, which makes sense: macros just manipulate bits of code. You only need math/array at runtime to create the actual value you end up with.

Is it possible to override bracket operators in ruby like endpoint notations in math?

Trying to implement something like this:
arr = (1..10)
arr[2,5] = [2,3,4,5]
arr(2,5] = [3,4,5]
arr[2,5) = [2,3,4]
arr(2,5) = [3,4]
Well, we need to override four bracket opreators: [], [), (], ()
Any ideas?
It's called "Including or excluding" in mathematics. https://en.wikipedia.org/wiki/Interval_(mathematics)#Including_or_excluding_endpoints
In short, this is not possible with the current Ruby parser.
The slightly longer answer: You'd have to start by modifying parse.y to support the syntax you propose and recompile Ruby. This is of course not a terrible practical approach, since you'd have to do that again for every new Ruby version. The saner approach would be to start a discussion on ruby-core to see if there is sufficient interest for this to be made part of the language (probably not tbh).
Your wanted syntax is not valid for the Ruby parser, but it could be implemented in Ruby with the help of self-modifying code.
The source files need to be pre-processed. A simple regular expression can substitute your interval expressions with ordinary method syntax, i.e.
arr[2,5] -> interval_closed(arr,2,5)
arr(2,5] -> interval_left_open(arr,2,5)
arr[2,5) -> interval_right_open(arr,2,5)
arr(2,5) -> interval_open(arr,2,5)
The string holding the modified source can be evaluated and becomes part of the application just like a source file on the hard disk. (See instance_eval)
The usage of self-modifying code should be well justified.
Is the added value worth the effort and the complications?
Does the code have to be readable for other programmers?
Is the preprocessing practical? E.g. will this syntax occur in one or a few isolated files, or be spread everywhere?

C: Regular expression optimization | Saving state

Lets suppose i'd like to search through "AAAAAAAABBBBBBB" and "AAAAAAAACCCCCCCCCCC".
I search for a pattern "(AB|AC)".
Is there a way to saving the state of the search after searching the "AAAAAAAA" part and then continuing with the [B..] and [C..] part seperatly? so i need to search in [A..] only once.
i write a short pseudo code example to be more clear.
step one:
pattern = "(AB|AC)"
match("AAAAAAAA", pattern)
save_state()
step two:
match("BBBBBBB", pattern)
should the find match "AB"
step three:
restore_state()
match("CCCCCCCCCCC", pattern)
should find match "AC"
If you use a regex flavor that uses a (real) NFA/DFA approach (like RE2), you don't have to store something since every input character is (or should be) used only once (this could not get better).
If your flavor uses a backtracking algorithm, you might have luck. Some of these engines allow you to introduce a non-backtracking (aka possessive) part by using (?>x) or x{1}+ (where {1} could be any quantifier)
So in your case, it could be (if it's allowed)
(?>A)(B|C)
or
A{1}+(B|C)

Calling functions from plain text descriptions

I have an app which has common maths functions behind the scenes:
add(x, y)
multiply(x, y)
square(x)
The interface is a simple google- style text field. I want the user to be able to enter a plain text description -
'2*3'
'2 times 3'
'multiply 2 and 3'
'take the product of 2 and 3'
and get a answer mathematical answer
Question is, how should I map the text descriptions to the functions ? I'm guessing I need to
tokenise the text
identify key tokens (function names, arguments)
try and map token combinations to function signatures
However I'm guessing this is already a 'solved problem' in the machine learning space. Should I be using Natural Language Processing ? Plain text search ? Something else ?
All ideas gratefully received, plus implementation suggestions [I'm using Python/AppEngine; I know about NLTK and Whoosh]
[PS I understand Google does this already, at least for the first two queries on the list. I'm guessing they also go it statistically, having a very large amount of search data. I don't have a large amount of data available, so will need an alternative approach].
After you tokenise the text, you need parsing to get a syntax tree of your natural language phrase. Once you have this, you can map the parse tree to a mathematical expression, and then evaluate the expression. I do not think this is a solved problem. I would start with several templates, say the first two, and experiment. The larger the domain of possible descriptions, the harder the task is.
I would recommend some tool for provide grammar/patterns on text like SimpleParse for python http://www.ibm.com/developerworks/linux/library/l-simple.html. As java programmer I would prefer GATE or graph-expression.

How do I implement exceptions with nestable try-catch-finally statement with messages in C

I'm looking to implement exceptions with nestable try-catch-finally statement with messages in C using longjmp/setjmp.
I've managed to implement try-catch-else exceptions, they are not nestable. I'm also hoping to add messages to the exceptions. Any idea how I might be able to do it?
Dave Hanson has already done a really nice package of exception macros as part of his excellent book C Interfaces and Implementations. You could either use the code wholesale or learn from his techniques. For anyone who does a fair amount of C programming, the book is worth buying—it will change the way you change about C programming, and it will show you how to do object-oriented design in C.
For nesting: a stack-frame of current try/catch blocks.
Your try will be using setjmp to save to a jmpbuffer (I guess). If you've done a try, and hence are now in the scope of a try block and hit another try then you want to preserve the existing jmpbuffer and also create a new one - Push - and when catching you are longjmp-ing back to the point of the most recent try hence you Pop the latest jmpbuffer. So I think a stack-like model make sense for nested try/catch.
For implementation, I guess the simplest apporach is to reserve an array of jmpbuffers, hence limiting your try catch depth - but keeping it simple; Push and Pop just require you to track the index in that array.
For messages and other exception contents, a reserved area for "currentException".
Exception content. Keep it simple, define an Exception struct. A char array and an int. Keeping it simple, but not too simple, reserve an array of them so that you can support chaining.
For a throw you allow
throw ( "string", errcode )
Which simply zeros the array structure and makes one entry. And
catch ( exception )
Now can look in the array and finds the first entry, and then
throwChain ( "string", errcode)
Which adds the new exception to the array (if there is room, and if not can shuffle the array according some rule such as FIFO)
But, I've got to ask, why not just use C++?
Well, you cannot really implement exceptions in C since they are not supported by the language. The best you can do is emulate them using setjmp and longjmp and some diabolically clever macros.
A quick search turns up these links that may be useful to you:
Exceptions in C
Exception handling with longjmp()

Resources