Crystal equivalent shard for "pp" (pretty printing) - crystal-lang

What is the Crystal equivalent shard for "pp" used in Ruby for pretty printing complex data structures ?

PrettyPrint is a part of a Crystal stdlib.
In short, you can just do p obj for "inspect" style output, pp obj for "pretty inspect" style output.

Related

Technical background to the C++ fmt::print vs. fmt::format_to naming?

Why is it fmt::format_to(OutputIt, ...) and not fmt::print(OutputIt, ...)??
I'm currently familiarizing myself with {fmt}, a / the modern C++ formatting library.
While browsing the API, I found the naming a bit disjoint, but given my little-to-no experience with the library (and my interest in API design), I would like to get behind these naming choices: (fmt core API reference)
There's fmt::format(...) -> std::string which makes sense, it returns a formatted string.
Then we have void fmt::print([stream, ] ...) which also makes sense naming wise (certainly given the printf legacy).
But then we have fmt::format_to(OutputIt, ...) -> OutputIt which resembles, apart from the return type, what print does with streams.
Now obviously, one can bike shed names all day, but here the question is not on why we have format vs. print (which is quite explainable to me), but why a function that clearly(?) behaves like the write-to-stream-kind has been bundled with the format_... naming style.
So, as the question title already asks, is there a technical difference in how fmt::print(stream, ...) behaves when formatting to a streams vs. how fmt::format_to(OutputIt, ...) behaves when formatting to an output iterator?
Or was/is this purely a style choice? Also, given that the GitHube repo explicitly lists the fmt tag here, I was hoping that we could get a authoritative answer on this from the original API authors.
While it would be possible to name format_to print, the former is closer conceptually to format than to print. format_to is a generalization of format that writes output via an output iterator instead of std::string. Therefore the naming reflects that.
print without a stream argument on the other hand writes to stdout and print with an argument generalizes that to an arbitrary stream. Writing to a stream is fundamentally different from writing to an output iterator because it involves additional buffering, synchronization, etc. Other languages normally use "print" for this sort of functionality so this convention is followed in {fmt}.
This becomes blurry because you can have an output iterator that writes to a stream but even there the current naming reflects what high-level APIs are being used.
In other words format_to is basically a fancy STL algorithm (there is even format_to_n similarly to copy/copy_n) while print is a formatted output function.

How to scan through user input and cut it into chunks in c++?

I'm making a program to evaluate conditional proposition (~ or and -> <->). As the users input propositional variables and truth values (true, false) ,and proposition; the program will go through the inputs and return the truth value for the whole proposition.
For ex: if i set p = true, q = true, r = false and input: p or q and r.
Is the anyway I can cut it into q and r first, then process and put it back to result (which is false), then process the next bit (p or false) ??. And it has to keep cutting out bits (In proper order of Precedence) and putting them back until I have left is a single true or false.
And what I'm I supposed to use to hold user input (array, string) ???
Any help would be appreciated ! Thanks.
Tasks like this are usually split into two phases, lexical analysis and syntactic analysis.
Lexical analysis splits the input into a stream of tokens. In your case the tokens would be the operators ~, or, and, ->, <->, variables and the values true, false. You didn't mention them but I'd imagine you also want to include brackets as tokens in your language. Your language is simple enough that you could just write the lexical analyser yourself but tools such as flex or ragel might help you.
Synyactic analysis is where you tease out the syntactic structure of your input and perform whatever actions you need (evaluate the preposition in your case). Syntactic analysis is more complex than lexical analysys. You could write a recursive descent parser for this task, or you could use a parser generator to write the code for you. The traditional tool for this is called bison, but it's a bit clunky. I like another simple tool called the lemon parser generator although it's more C orientated than C++.

Printing internal representation of a Coq term

How to print the internal OCaml representation of a term in Coq (exposing the data constructors like Lambda, App, Rel, etc... )?
Is there any equivalent of derived show, as in Haskell, in OCaml?
You can print the body of any Coq term using the vernacular command Show. There is a lot of notations in Coq that can hide some terms, so you can also deactivate the notations using CoqIDE's menu, or using the command Set Printing All. in coqtop/ProofGeneral, prior to calling Show.
However this will expose the term in the Coq language, not it's OCaml encoding. If you want the underlying Ocaml representation, I guess you'll have to hack a bit Coq's code. I am not aware of any such command as for today.
For the show type class, I don't think there is one in the std, by I might mistaken.

How to interpret a custom language

I have an app in C++ which actually processes a binary file. The binary file is a collection of events say A/B/C, and on detecting event A in the file, the app handles the event in "handler A".
Now i need to write another script in a custom language, which gets executed orthogonally to the binary file processing. The script can have something like,
define proc onA
{
c= QueryVariable(cat)
print ( c )
}
So when the app handles the event "A" from the binary file, the app has to parse this script file, check for OnA and convert the statements in OnA proc to routines supported by the app. For eg, QueryVariable should copy the value of variable "cat" defined in the app to the variable "C". The app should also check for syntax/semantics of the language in script. Where can i get the best info for deciding on the design? My knowledge on parse trees/grammar has really weakened.
Thanks
An easy way to build an interpreter:
Define a parser for the language from its syntax
Build an abstract syntax tree AST
Apply a visitor function is traverse the AST in preorder and "execute" actions suggested by the AST nodes.
Some AST nodes will be "definitional", e.g., will declare the existence of some named entity such as your "define proc onA " phrase above. Typically the action is to associate the named entity with the content, e.g., form a triplet <onA,proc,<body>> and store this away in a symbol table indexed by the first entry. This makes finding such definitions easier.
Later, when your event process encounters an A event, your application knows to look up "onA" in this symbol table. When found, the AST is traversed by the visitor function to execute its content. You'll usually need a value stack to record intermediate expression values, with AST leaves representing operands (variables, constants) pushing values onto that stack, and operators (+, -, <=) popping values off and computing new results to push. Assignment operations take the top stack value and put into the symbol table associated with the identifier name. Control operators (if, do) take values off the top of the stack and use them to guide what part off the program (e.g., what subtree) to execute next.
All of this is well known and can be found in most books on compilers and interpreters. Peter Brown's book on this is particularly nice even though it seems relatively old:
Writing Interactive Interpreters and Compilers.
There must be some interpreter or compiler for the scripting language. Check if it supports embedding in C or C++. Most script languages do.
Next choice, or perhaps first, would be to just run the script externally, using the existing compiler/interpreter.
I can't think of any reason why one of the first two options won't do, but if not, consider building an interpreter using ANTLR or for a small language Boost Spirit. Disclaimer: I haven't used the first, and I've only tried out Boost Spirit for a small toy example.
Cheers & hth.,
PS: If you can choose the script language, consider JavaScript and just use Google's reportedly excellent embedding API.

Expression Evaluation in C++

I'm writing some excel-like C++ console app for homework.
My app should be able to accept formulas for it's cells, for example it should evaluate something like this:
Sum(tablename\fieldname[recordnumber], fieldname[recordnumber], ...)
tablename\fieldname[recordnumber] points to a cell in another table,
fieldname[recordnumber] points to a cell in current table
or
Sin(fieldname[recordnumber])
or
anotherfieldname[recordnumber]
or
"10" // (simply a number)
something like that.
functions are Sum, Ave, Sin, Cos, Tan, Cot, Mul, Div, Pow, Log (10), Ln, Mod
It's pathetic, I know, but it's my homework :'(
So does anyone know a trick to evaluate something like this?
Ok, nice homework question by the way.
It really depends on how heavy you want this to be. You can create a full expression parser (which is fun but also time consuming).
In order to do that, you need to describe the full grammar and write a frontend (have a look at lex and yacc or flexx and bison.
But as I see your question you can limit yourself to three subcases:
a simple value
a lookup (possibly to an other table)
a function which inputs are lookups
I think a little OO design can helps you out here.
I'm not sure if you have to deal with real time refresh and circular dependency checks. Else they can be tricky too.
For the parsing, I'd look at Recursive descent parsing. Then have a table that maps all possible function names to function pointers:
struct FunctionTableEntry {
string name;
double (*f)(double);
};
You should write a parser. Parser should take the expression i.e., each line and should identify the command and construct the parse tree. This is the first phase. In the second phase you can evaluate the tree by substituting the data for each elements of the command.
Previous responders have hit it on the head: you need to parse the cell contents, and interpret them.
StackOverflow already has a whole slew of questions on building compilers and interperters where you can find pointers to resources. Some of them are:
Learning to write a compiler (#1669 people!)
Learning Resources on Parsers, Interpreters, and Compilers
What are good resources on compilation?
References Needed for Implementing an Interpreter in C/C++
...
and so on.
Aside: I never have the energy to link them all together, or even try to build a comprehensive list.
I guess you cannot use yacc/lex (or the like) so you have to parse "manually":
Iterate over the string and divide it into its parts. What a part is depends on you grammar (syntax). That way you can find the function names and the parameters. The difficulty of this depends on the complexity of your syntax.
Maybe you should read a bit about lexical analysis.