tcl programming exercises
In these Tcl experiments, I use "" for "" and angle-brackets <> for the overbar-hook (with zero or more operands in between). Tcl is used for web applications, desktop GUIs, testing and automation, and more. (I might have called it fun as well it sure is.) Tcl is a general purpose multi-paradigm system programming language. 560 pages, Paperback. Execution starts at the first of the states. #puts "$mem($pc)\tA:$::A B:$::B C:$::C D:$::D E:$::E Z:$::Z", #----------------- "machine opcodes" implemented as procs, ; idiomatic: get over the initial variable(s), ; load double registers H+L with the address INCR, ; load byte to register B from the address pointed to in HL, "$body \$x [string repeat \] [llength $args]]". The following scripts are plain Tcl, they don't use the Tk GUI toolkit (there's a separate chapter for those). Newbie Tcl/Tk exercises. Note that on infinite streams, selectors may never return, e.g. So an "assembler" program in this plaything will run even slower than in pure Tcl, and consume more memory while normally you associate speed and conciseness with "real" assembler code. The author (Richard Suchenwirth) declares them to be fully in the public domain. Of course, with growing databases we may reach memory limits: arrays need some extra storage for administration. Let's change that "a" can have only two values, "" or <>, so we might try to solve the expression by assuming all possible values for a, and see if they differ. personal mentoring, TCL Scripting Training. So what about a thin abstraction (wrapper) around this recurring pattern? They are for instance the building blocks of relational databases and spreadsheets. They always return a result (even if it is the empty string ""), so to call them functions might be most appropriate. The numbers of the bits finally still set are supposed to be primes, and returned: Here's code to count the number of 1-bits in a bit vector, represented as an integer list. There are over 200 exercises with solutions for both Unix and Windows platforms. Such process chains can be emulated in Tcl with the following rules: A stream is modelled here as a procedure that returns one stream item on each call. }, can be represented by their truth table, which for example for {$a && $b} looks like: As all but the last column just enumerate all possible combinations of the arguments, first column least-significant, the full representation of a&&b is the last column, a sequence of 0s and 1s which can be seen as binary integer, reading from bottom up: 1 0 0 0 == 8. Enrol for e-learning course for self paced learning. # - rewrite a proc's default arg with given value. in the forum After some head-scratching, I find it plausible, and possibly it is even the simplest possible solution, given the poorness of this RPN language. An important functional form is the conditional, which at Backus looks like. Tcl Scripting Basic Examples Introducing 4th Gen Intel Xeon Scalable Processors Introducing 4th Gen Intel Xeon Scalable Processors Introducing 4th Gen Intel Xeon Scalable Processors The browser version you are using is not recommended for this site. In truly brute force, up to half a million programs are automatically written and (a suitable subset of them) tested to find the one that passes the tests. 4. Running a Tcl/Tk applet within a Tcl/Tk program. Most of these example scripts first appeared in the Tclers' Wiki http://wiki.tcl.tk . However, this is no fundamental problem consider that. The entire syntax of Tcl is described in just 12 rules. Should you need a unit matrix (where the main diagonal is 1, and the rest is 0), just call outProd with a different function (equality, ==): which just requires expr's equality to be exposed too: One of the fascinations of functional programming is that one can do the job in a simple and clear way (typically a one-liner), while using a collection of reusable building-blocks like lmap and iota. The set of all defined bytecodes will be the alphabet of this little RPN language. execution of the script "++" should sum its three arguments (1+(2+3)), and return 6. The correct hypot() function would be. Tcl - Environment Setup . Indexes: As shown, we can retrieve all data by sequential searching over array names. An obvious string representation of a rational is of course "n/d". See all Tcl exercises Get started with the Tcl track The best part, it's 100% free for everyone. to make it understand and do things that before raised an error, the easiest way is to write a proc. But for historical reasons, the Tcl command to create a function is called proc and thus people most often call them procedures. Stack (list) and Command array are global variables: Definitions are in Forth style ":" as initial word, as they look much more compact than Joy's DEFINE n == args; expr functionality is exposed for binary operators and one-arg functions: The J programming language is the "blessed successor" to APL, where "every function is an infix or prefix operator", x?y (dyadic) or ?y (monadic), for ? lines make the self-test; otherwise they just illustrate how the operations should work. Discussion: With the above code, it was possible to reproduce quite some behavior of streams as documented in SICP, not as data structures but with Tcl procs (though procs are data too, in some sense). What's missing is the capability to randomly address parts of a stream, as is possible in Scheme (and of course their claim to do without assignment, or mutable data) Tcl lists just don't follow LISP's CAR/CDR model (though KBK demonstrated in Tcl and LISP that this structure can be emulated, also with procs), but rather C's flat *TclObject[] style. These 20 syntax will definitely help you lot to start and improve your tcl scripting a lot. Consider the following model: Fields may well be implemented as array entries, so we could have an array per record, or better one array for the whole database, where the key is composed of ID and tag. Unique IDs can be had by just counting up (incrementing the highest ID so far). Maybe another weekend John Backus turned 80 these days. In a very radical simplification, a whole world is built up by two operators, juxtaposition without visible symbol (which could be likened to or) and a overbar-hook (with the meaning of not) that I can't type here it's a horizontal stroke over zero or more operands, continued at right by a vertical stroke going down to the baseline. And that is one, and not the worst, Tcl way of Tacit programming APL and J (see Tacit programming) have the feature that arithmetics can be done with vectors and arrays as well as scalar numbers, in the varieties (for any operator @): Here's experiments how to do this in Tcl. ACM 21.8, Aug. 1978, 613-641), he developed an amazing framework for functional programming, from theoretical foundations to implementation hints, e.g. Tcl/Tk 8.5 Programming Cookbook (2011) , by Bert Wheeler, provides over 100 recipes to effectively use Tcl/Tk 8.5. $ mkdir ~/cs498gpl/exercises/tcl $ cd ~/cs498gpl/exercises/tcl. Here single bracing is correct. Implement an evaluator for a very simple subset of Forth. Doing more steps towards functional programming, I came upon this interesting problem, and will shortly demonstrate that it can easily be solved in pure-Tcl. Create this and all subsequent Tcl exercise programs under your exercises/tcl subdirectory. All bits are initialized to 0. I added converters between characters and integers, and between strings and lists (see the dictionary below). Tcl is a string based scripting language. Develop fluency in 67 programming languages My "Def" creates an interp alias, which is a good and simple Tcl way to compose partial scripts (the definition, here) with one or more arguments, also known as "currying": The second parameter, "=", is for better looks only and evidently never used. Join Exercisms Tcl Track for access to This may be used for Boolean properties of numerically indexed sets of items. Coroutines allow asynchronous interleaved tasks to be written in a sequential style. Tcl's lists are well suited to represent sets. In an RPN language, the example might look like this: which has the advantage that execution goes from left to right, but requires some stack awareness (and some swaps to set the stack right;^), Implementing Def, I took an easy route by just creating a proc that adds an argument and leaves it to the "functional" to do the right thing (with some quoting heaven:-) }. Rather, one could use read and write traces on variable M, causing it to load from, or store to, mem($HL). This video covers the basics that you need to start writing scripts with Tool Command Language (TCL or Tickle).Following topics are explained with simple exa. # Here is another stream producer that returns elements from a list: # This one repeats its list endlessly, so better use it with 'more': # This is sugar for first-time assignment of static variables: # But for a simple constant stream source, just use [subst]: # more {subst 1};# will produce as many ones as you wish. Let us write a simple Tcl program. Getting more daring, let's try a distributive law: Daring more: what if we postulate the equivalence? The pattern, is a kind of conditional in J, which could in Tcl be written. (One might truncate the list at front if it gets too long). This can be plugged into a filter chain to see what's going on: # or, to get a stream of even numbers, starting from 0: "to recall is to call -- (1 || 1) == 1", "PONG [info hostname] [lindex [split $line] 1]", "Try http://wiki.tcl.tk/[lindex $args end]", "Why do [string map {I you my your your my you me} $args]? In Tcl, a sensible implementation for compact data storage would be as a list of lists. Ramanujan numbers: The pairs generator can be used to find Ramanujan numbers, which can be represented as the sum of two integer cubes in more than one way. Rules are also taken as strings, whose parts can easily be extracted with string index as it's used so often here, I alias it to @. Easily done in a few lines of Tcl code: The code does not directly puts its results, but returns them as a string you might want to do other things with it, e.g. Implication (if a then b, a -> b) can in expr be expressed as $a <= $b just note that the "arrow" seems to point the wrong way. Explore the Tcl exercises on Exercism Unlock more exercises as you progress. The coin values should be passed to change as a variable number of arguments which are the coin values in units (e.g., a quarter would be represented as 25) in any order. Assume John Smith borrows "The Tempest". Chapter 4 discusses Tcl I/O support for les, pipes, and sockets. They think it's a programing (like software programing) and they are in VLSI Industry to do some hardware related job. The source code is compiled into bytecode, which is later interpreted by the Tcl interpreter. The goto command is defined "locally", and deleted after leaving the state machine it is not meaningfully used outside of it. The following code was created in the Tcl chatroom, instigated by the quote: "A computer is a state machine. Filters may be characterized as "selectors" (who may return only part of their input, like "grep") and/or "appliers" who call a command on their input and return the result. Here I want to explore how a database can be implemented in the Tcl spirit of simplicity, and how far that approach takes us. Note that with this mapping, all valid programs (bytecode sequences) correspond to one unique non-negative integer, and longer programs have higher integers associated: Now out for discovery! The first and second arguments are the class (disregarded here, as the dash shows) and the value, the rest is up to the coder. Get better at programming through fun, rewarding coding exercises that test your understanding of concepts with Exercism. Discover new exercises as you progress and get engrossed in learning new concepts and improving the way you currently write. But func isn't limited to math functions (which, especially when recursive, come out nice), but for expr uses in testing predicates as well: Exposing expr binary arithmetic operators as Tcl commands goes quite easy too: For "-", we distinguish unary and binary form: Having the modulo operator exposed, gcd now looks nicer: For unary not I prefer that name to "! The extending code what is prepended to the previous unknown body. The absence of lexical scoping also led to constructs like sproc/reset, which stop a gap but aren't exactly elegant but Tcl's clear line between either local or global variables allows something like closures only by rewriting default arguments like done in remember (or like in Python). From Grade School to Raindrops. This code for transposing a matrix uses the fact that variable names can be any string, including those that look like integers, so the column contents are collected into variables named 0 1 2 and finally turned into the result list: An integer range generator produces the variable names, e.g iota 3 => {0 1 2}. The following "constructor" does that, plus it normalizes the signs, reduces to lowest terms, and returns just the integer n if d==1: Conversely, this "deconstructor" splits zero or more rational or integer strings into num and den variables, such that [ratsplit 1/3 a b] assigns 1 to a and 3 to b: Arithmetical helper functions can be wrapped with func if they only consist of one call of expr: Languages like Lisp and Python have the docstring feature, where a string in the beginning of a function can be retrieved for on-line (or printed) documentation. For instance, if you would like to simplify the for loop, for the typical simple cases so you can write instead. That's easily had too, given a sum function: Here's a little application for this: a vector factorizer, that produces the list of divisors for a given integer. is building a list of the floor and the ceiling of its single argument, the comma being the concatenation operator here, comparable to Backus' "construction" or Joy's cleave. # make a list of 2**n lists, each with n truth values 0|1, #-- And here's some more hand-crafted bytecode implementations, #-- The stack routines imply a global stack::S, for simplicity, # a bytecode will consume at most two elements, #-- make a table of bytecode stack balances, #-- "peephole optimizer" - suppress code with redundancies. here is an implementation that even returns a list of the results of each iteration: using this, a string reverse function can be had as a one-liner: Another example is the following range-aware switch variation. Tk is an extension, developed by the creator of Tcl, used for creating scripts that interact with users through windows. Book . The partitioning helps very much in reducing the number of candidates. The memory model is constant-size instructions (strings in array elements), which are implemented as Tcl procs. {AND, OR, NOT} resp. Of course this is no real assembler. Another example is this integer range generator (starts from 1, and is inclusive, so [iota1 5] == {1 2 3 4 5}): "NAND is not AND." Here is a simple example of a "chat bot" a program that listens on an IRC chatroom, and sometimes also says something, according to its programming. Hence, streams can be (and typically are) nested for processing purposes. But if the database grows in size, it's a good idea to create indexes which cross-reference tags and values to IDs. Another test, inequality: Trying to call 14 (OR) with more than two args: The constant 0 result is a subtle indication that we did something wrong:). Say you want to make a multiplication table for an elementary school kid near you. #-- We can compute the modulo of a number by its index vector: #-- and turn all elements where the remainder is 0 to 1, else 0: #-- Hence, 7 is only divisible by 1 and itself, hence it is a prime. Also, memory limits on modern computers are somewhere up high so only at some time in the future you might have (but maybe not want) to change to a complex database;-). This looks better to me than /slashing as in Postscript. So, on a morning dogwalk, I thought out this strategy: Here's this version. Exercise 1 - Tcl procedure. Sorting roman numerals: I,V,X already come in the right order; for the others we have to introduce temporary collation transformations, which we'll undo right after sorting: As "control structures" are really nothing special in Tcl, just a set of commands, it is easier than in most other languages to create one's own. Like in switch, fall-through collapsing of several cases is indicated by "-", and "default" as final condition fires if none else did. For porting this, lmap is a good helper, even though not strictly functional: We furtheron borrow some more content from expr: We'll need functional composition, and here's a recursive de-luxe version that takes zero or more functions, hence the name o*: is the neutral element of variadic functional composition, when called with no functions at all. OO (Object Orientation) is a style in programming languages popular since Smalltalk, and especially C++, Java, etc. Adding "records" to the table is as easy as. and the experimental alpha version 8.1/8.1. Just choose how to implement instance variables: The task of frameworks, be they written in Tcl or C, is just to hide away gorey details of the implementation in other words, sugar it:) On the other hand, one understands a clockwork best when it's outside the clock, and all parts are visible so to get a good understanding of OO, it might be most instructive to look at a simple implementation. In SICP chapter 3.5, streams are introduced as data structures characterized as "delayed lists", whose elements are produced and returned only on demand (deferred evaluation). But for n>143 we reach the domain limit of floating point numbers. Practical Programming in Tcl and Tk by Brent Welch, Ken Jones. However, as integer division takes place, it would be better to make that. Now we can write n(f), which, given a Boolean function of one or more arguments, returns its characteristic number, by iterating over all cases in the truth table, and setting a bit where appropriate: So the characteristic integer is not the same as the Goedel number of a function, which would encode the structure of operators used there. To make things easier, this flavor of "software" is in a very simple RPN language similar to, but much smaller than, the one presented in Playing bytecode: stack-oriented like Forth, each operation being one byte (ASCII char) wide, so we don't even need whitespace in between. if someone mentions its name (minibot), tries to parse the message and answer. This is something like the Goedel number of the corresponding code. As a second step, we create the If command that wraps the expr invocation: This again passes impromptu tests, and adds the feature that any non-zero value counts as true and returns 1 if we neglect the other syntactic options of if, especially the elseif chaining. For instance, if the test has two inputs and wants one output, the stack balance is -1 (one less out than in). Learn and practice Tcl by completing 122 exercises that explore different concepts and ideas. Especially, indexing the isa field allows iterating over "tables" (which we still don't explicitly have! of your code and Tests are done with this minimal "framework": The dot product of two vectors is a scalar. Tcl has no goto command, but it can easily be created. In addition to extensive program-ming work on Tcl, Clif offers Tcl/Tk training sessions with in-class exercises. in static variables (here implemented with the fancy remember proc) examples are intgen that delivers ever increasing integers, or gets $fp where the file pointer advances at each call, so potentially all lines of the file are returned over time. So let's get the pieces together. Just say "Hello, World!". Tcl/Tk for Programmers is an introduction to the high-level Tcl/Tk scripting language for experienced programmers with either Unix or Windows background. 2. looking for: Tcl/Tk exercises (please) 3. with automatic analysis If composite functions like 'fork' are arguments to o*, we'd better let unknown know that we want auto-expansion of first word: Also, we need a numeric sort that's good for integers as well as reals ("Def" serves for all kinds of aliases, not just combinations of functions): As this file gets tacitly sourced, I am pretty confident that I've reached my goal for this weekend even though my median doesn't remotely look like the J version: it is as "wordy" as Tcl usually is. Running other programs from Tcl - exec, open Channel I/O: socket, fileevent, vwait More channel I/O - fblocked and fconfigure Communicating with other programs - socket, fileevent Time and Date - clock Using databases Introspection, Debugging and Performance Learning the existence of commands and variables - info State of the interpreter - info {&&, ||,! 100% free. The size of partitions is further reduced by excluding programs which contain redundant code, that will have no effect, like swapping the stack twice, or swapping before an addition or multiplication. The source files for Tcl programs are named with the extension ".tcl". Here we can do what we want, even retrieve which fields we have used so far (using a temporary array to keep track of field names): Searching for records that meet a certain condition can be done sequentially. Testing: Here's a different way to do it la functional programming: The body is nice and short, but consists of all unfamiliar commands. If both the operands are non-zero, then condition becomes true. 13Solving cryptarithms 14Database experiments 14.1A simple array-based database 14.2Tables as lists of lists 15Programming Languages Laboratory 15.1GOTO: a little state machine 15.2Playing Assembler 15.3Functional programming (Backus 1977) 15.4Reusable functional components 15.5Modelling an RPN language 15.6Tacit programming 16Vector arithmetics ;-): And beyond industry-standard SQL, we can search multiple indices in one query: gives you all (case-independent) occurrences of MARK, be it in patron's names, book's authors or titles. The discoverer, Second Edition, determines the stack balance of the first text, and tests only those programs of the same partition: But now for the trying. Grade School Given students' names along with the grade that they are in, create a roster for the school. I only had to take care that when moving beyond its ends, I had to attach a space (written as _) on that end, and adjust the position pointer when at the beginning. In the next step, I want to reimplement the "median" function, which for a sorted list returns the central element if its length is odd, or the mean of the two elements adjacent to the (virtual) center for even length. And three nested calls to vec are sufficient to produce the divisors list:). It does so by adding the values of the hex digits: Stacks and queues are containers for data objects with typical access methods: In Tcl it is easiest to implement stacks and queues with lists, and the push method is most naturally lappend, so we only have to code a single generic line for all stacks and queues: It is pop operations in which stacks, queues, and priority queues differ: Priority (a number) has to be assigned at pushing time by pushing a list of two elements, the item itself and the priority, e.g.. Runtime of bit vector accesses is constant, except when a vector has to be extended to much larger length. ", as it might also stand for factorial and see the shortest function body I ever wrote:^): Without big mention, functions implemented by recursion have a pattern for which func is well suited (see fac and gcd above). This is provided e.g. Clif first learned to program in high school in machine language on a Monroe 600 programmable . If a field content contains spaces, it must be quoted or braced too: Sorting a table can be done with lsort -index, taking care that the header line stays on top: Removing a row (or contiguous sequence of rows) by numeric index is a job for lreplace: Simple printing of such a table, a row per line, is easy with. See the examples soon to come. A math book showed me the Stirling approximation to n! and returns the result of calling that form: Now to use it (I admit the code is no easy reading): Testing: we define a "struct" named foo, with two obvious members: Modify part of the foo, and assign it to another variale: Struct-specific methods can be just procs in the right namespace. Rational numbers, a.k.a. Chapters 5-8 introduce more commands and techniques and For functional composition, where, say for two functions f and g. again a proc is created that does the bracket nesting: Why Backus used Transpose on the input, wasn't first clear to me, but as he (like we Tclers) represents a matrix as a list of rows, which are again lists (also known as vectors), it later made much sense to me. In that situation, you can fall back to the (otherwise slower, and uglier) use of a dedicated iterator: But neither can you filter the keys you will get with a glob pattern, nor may you add or delete array elements in the loop the search will be immediately terminated. Adding a book to the database can be simply done by, Note that, as we never specified what fields a record shall contain, we can add whatever we see fit. Tcl/Tk 8.2.3 and Tcl/Tk 8.3.0 under windows. As we've seen that
Problems With Benelli M2,
Office 365 The Following Files Couldn T Be Attached,
Pathfinder: Kingmaker Magus,
Acme Markets Employee Apparel,
Social Security Administration Employee Directory,
Articles T