<![CDATA[Code Ballads]]>https://code-ballads.net/https://code-ballads.net/favicon.pngCode Balladshttps://code-ballads.net/Ghost 2.7Sun, 22 Nov 2026 06:04:33 GMT60<![CDATA[Dear ImGui Bundle: (web) apps in pure Python with a single code base]]>https://code-ballads.net/dear-imgui-bundle-build-real-time-python-web-applications-with-zero-fuss/6864d0bc3907090001a45880Sun, 06 Jul 2025 09:47:20 GMT

Thanks to Dear ImGui Bundle, which is now available inside Pyodide (a web distribution of Python), it is now possible to develop sophisticated GUI and apps in Python with a code that :

  • can be used to deploy to full desktop applications
  • or run (with the same code) in the browser, without requiring a distant server, and without relying on any HTML / DOM / Javascript
  • provides access to numerous widgets and libraries (widgets, scientific plotting,  image analysis, etc)
  • is highly readable

Minimal demonstration

Here is a minimal demo that draws an animated heart with and adjustable heart beat.

Dear ImGui Bundle: (web) apps in pure Python with a single code base
Launch demo

Its code is surprisingly short: it fits in a single 50 lines file,  almost entirely in Python (with a bit of HTML and JavaScript).

Since pyodide's distribution is available via a CDN, you can reproduce this on your side : just copy-paste code below into a html file (click here for a copyable version of the source code).

Dear ImGui Bundle: (web) apps in pure Python with a single code base

Online playground

An online playground will enable you to run and edit various ImGui applications in the browser without any setup.

Dear ImGui Bundle: (web) apps in pure Python with a single code base
An image processing application, with a sophisticated image viewer
Dear ImGui Bundle: (web) apps in pure Python with a single code base

Comparison with traditional web python libraries

Tools like Streamlit and Gradio abstract away much of the boilerplate when building a Web Gui with  Python, and simplify the bridge between Python and the browser.
However, when things break, you're suddenly wrestling with  JavaScript errors, layout issues in CSS, or debugging the client-server synchronization:

Dear ImGui Bundle: (web) apps in pure Python with a single code base

This is where using a tool like ImGui Bundle shines : apps developed with Dear ImGui Bundle never use any HTML element (button, etc), each call is synchronous, and everything that you see is drawn via calls to the GPU.


In this article

  • We explain how Immediate Mode GUI works
  • We introduce Dear ImGui, a reputable Immediate Mode GUI library (C++)
  • We explore ImGui Bundle, which brings Dear ImGui to Python, together with lots of utilities
  • And we show how it all works in your browser, with Pyodide

The Immediate Mode GUI Paradigm

What is Immediate Mode GUI?
Immediate Mode GUIs (IMGUI) differ from traditional  retained-mode frameworks. Instead of building and maintaining an  abstract UI tree, you declare your widgets at each frame — just like  calling print() repeatedly in a loop.

This approach leads to:

  • Simple, stateless, and readable code
  • Full control over rendering and logic, frame-by-frame
  • Great debugging and introspection: there's no hidden state behind the GUI

For instance, displaying button and handling its action in ImGui might just look like:

Dear ImGui Bundle: (web) apps in pure Python with a single code base

Compared to retained-mode and web-based GUIs

Frameworks like Streamlit and Gradio rely on a layered architecture that separates logic from rendering.

In contrast, Immediate Mode GUIs are radically simple:
There’s no event queue to wire, no hidden reactive state —  just Python code running in a loop, directly rendering the GUI. Whether you run it natively or in the browser via Pyodide, the UI logic stays  local, explicit, and easy to debug.

Comparison: Immediate Mode vs classic Python Web GUIs

Dear ImGui Bundle: (web) apps in pure Python with a single code base

Enter Dear ImGui

Dear ImGui is a fast, lightweight C++  library designed for building rich graphical user interfaces in  real-time applications. Originally developed for debugging tools in game engines, it's now used across industries for visualization, simulation,  embedded UIs, and more.

ImGui follows the Immediate Mode GUI paradigm: widgets are declared directly in your rendering loop, which makes it incredibly responsive, debuggable, and easy to integrate.

Dear ImGui is known for:

  • Extremely high performance (everything is drawn via the GPU)
  • A focus on developer productivity and iteration speed
  • A powerful ecosystem: plotting (ImPlot), markdown, node editors, etc.

With 66k+ GitHub stars and a passionate community, ImGui has become a go-to for developers who want full control and minimal friction when building UIs.

Meet Dear ImGui Bundle

Dear ImGui Bundle builds on top of Dear  ImGui to offer a ready-to-use, cross-platform toolkit for both C++ and  Python.
It comes with batteries included, as it includes the core of ImGui, together with  advanced  widgets and libraries, for plotting (ImPlot and ImPlot3d), image handling, markdown rendering, node  editors, and more.

It provides documented Python bindings for ImGui and all the included libraries. These bindings are auto-generated, which means, that they will always be up to date with the latest versions.

An ideal framework for prototyping and exploration

Dear ImGui Bundle is a great match for data scientists, educators, and toolmakers who want to tests their ideas and build prototypes quickly, without giving up control.

ImGui Bundle in the Browser (via Pyodide)
Thanks to its availability in Pyodide, ImGui Bundle is now a Python GUI framework that works  identically across desktop and browser, with the same codebase.

Of course, there are some limitations due to the web environment: sandboxing, no filesystem access, etc. The pyodide wheel is relatively small at 4.5MB.

Test it

On your computer

Dear ImGui Bundle is available on pypi.

pip install imgui-bundle  # MIT license

On the web

You can download the Pyodide distribution with ImGui Bundle pre-installed from the following link: Download Pyodide with ImGui Bundle

ImGui Bundle was just added to the official Pyodide recipes, so you will be able to use it without downloading anything in the future. See relevant PR

]]>
<![CDATA[An overview of recent progress and challenges in AI]]>If ChatGPT is today at the heart of the debate, it is already almost part of the past: its successors are being born these weeks.

New multimodal robots are emerging. Going far beyond image creation, or answering questions, they are conversational robots with long arms: they can read and write

]]>
https://code-ballads.net/an-overview-of-recent-progress-and-challenges-in-ai/644d429419c36e0001a0a911Sat, 29 Apr 2023 16:19:06 GMTIf ChatGPT is today at the heart of the debate, it is already almost part of the past: its successors are being born these weeks.

New multimodal robots are emerging. Going far beyond image creation, or answering questions, they are conversational robots with long arms: they can read and write on the internet, generate and analyze texts, images and videos, recognize and imitate voices, write and execute programs, make phone calls, etc.  They are extremely easy to use, especially because they are programmed in plain English, and bound to become extremely powerful.

They are also becoming dangerous, since automated mass manipulations and scams are becoming easy. These robots are rapidly being democratized, since versions are now available in open source. 2023 might be a pivotal year.

The article linked below aims to try to get ahead of the curve by trying to predict what is coming in a few months, and analyses some possible solutions and regulations.

Links to the article (pdf):

I have gathered this data because it is a subject that both fascinates and worries me, and I hope that enlightened information can help to better understand it.

On the same subject, the authors of "The Social Dilemma" have also published a video that I recommend: The AI Dilemma.


Si ChatGPT est aujourd'hui au cœur du débat, il fait déjà presque partie du passé : ses successeurs naissent ces semaines-ci.

De nouveaux robots multimodaux émergent. Bien au-delà de la création d'images ou de la réponse à des questions, ce sont des robots conversationnels avec de longs bras : ils peuvent lire et écrire sur internet, générer et analyser des textes, des images et des vidéos, reconnaître et imiter des voix, écrire et exécuter des programmes, passer des appels téléphoniques, etc.  Ils sont extrêmement faciles à utiliser, notamment parce qu'ils sont programmés en anglais de tous les jours, et sont appelés à devenir extrêmement puissants.

Ils deviennent également dangereux, car les manipulations de masse automatisées et les escroqueries sont de plus en plus faciles. Ces robots se démocratisent rapidement, puisque des versions sont désormais disponibles en open source. 2023 pourrait être une année charnière.

L'article ci-dessous a pour but d'essayer de prendre de l'avance en essayant de prédire ce qui se passera dans quelques mois, et analyse quelques solutions et réglementations possibles.

Liens vers l'article (pdf) :

J'ai rassemblé ces données car c'est un sujet qui me passionne et m'inquiète à la fois. Il est grand temps que les citoyens s'en emparent et j'espère qu'une information éclairée pourra y contribuer.

Sur le même sujet, les auteurs de "The Social Dilemma" ont également publié une vidéo que je recommande : The AI Dilemma.

]]>
<![CDATA[Annoucing ImmVision]]>ImmVision (a.k.a Immediate Vision) is an image debugger and viewer.

ImmDebug: standalone Image Debugger (during execution, and post-mortem)

Video tutorial on Youtube

immvision includes an advanced image debugger for OpenCV which you  can easily plug into your C++ projects in order to be able to visually  debug images

]]>
https://code-ballads.net/annoucing-immvision/63d43e4d1e64240001f6708eFri, 27 Jan 2023 21:18:36 GMTImmVision (a.k.a Immediate Vision) is an image debugger and viewer.

ImmDebug: standalone Image Debugger (during execution, and post-mortem)

Video tutorial on Youtube

immvision includes an advanced image debugger for OpenCV which you  can easily plug into your C++ projects in order to be able to visually  debug images inside your image processing algorithms, during execution  or even after execution (post-mortem).

This requires no dependency apart from OpenCV, and you do not need to link your program to immvision (you will just need to copy 4 cpp files in your project).

The immdebug application

Image Viewer

Video tutorial on YouTube

This image viewer runs inside ImGui (and thus your program must be linked to it).

This viewer is also included inside ImGui Bundle, where it can also be used from python.

The API can be summarized as

IMMVISION_API void Image(const std::string& label, const cv::Mat& mat, ImageParams* params);

See Full API

See online demo!

]]>
<![CDATA[Announcing Dear ImGui Bundle]]>

Dear ImGui Bundle is a quick-start and all-batteries-included framework to create cross-platform apps with Dear ImGui. It enables to easily create ImGui applications in C++ and Python, under Windows, macOS, Linux, and emscripten (and also iOS).

It is aimed at application developers, researchers, and who want to quickly develop apps

]]>
https://code-ballads.net/annoucing-dear-imgui-bundle/63d431d115729500019aac6eFri, 27 Jan 2023 20:21:29 GMTAnnouncing Dear ImGui BundleAnnouncing Dear ImGui Bundle

Dear ImGui Bundle is a quick-start and all-batteries-included framework to create cross-platform apps with Dear ImGui. It enables to easily create ImGui applications in C++ and Python, under Windows, macOS, Linux, and emscripten (and also iOS).

It is aimed at application developers, researchers, and who want to quickly develop apps and prototypes, taking advantage of the Immediate Gui paradigm.


Included libraries:

Dear ImGui Bundle includes the following libraries:


This annoucement is voluntarily short, since ImGui Bundle also introduces a somewhat innovative way to present its documentation, since the online demo is also the manual (you can also look at the web manual)


Some highlights with screenshots below:

Lots of widgets

Announcing Dear ImGui Bundle

Documentation via a markdow and snippets renderer

Announcing Dear ImGui Bundle

Example of a image processing tool developped with the included node editor (imgui-node-editor) and Image analysis (ImmVision) tools

Announcing Dear ImGui Bundle

A example with python inside Jupyter Notebook

Announcing Dear ImGui Bundle

Theming

Announcing Dear ImGui Bundle

Hello World, in C++ and Python

Announcing Dear ImGui Bundle
Note: this a a screenshot from the online interactive demo! ImGui Bundle includes its own documentation and snippets renderer
The python and C++ api are extremely close and fully documented, enabling an almost line by line transcription, which makes it a great fit for R&D teams who want to quickly develop research tools in python, and still be able to easily port them in production.

Announcements

]]>
<![CDATA[Discoverable algorithms in C++]]>https://code-ballads.net/discoverable-algorithms/5f9fde9cafe6800001160235Mon, 02 Nov 2020 14:18:01 GMTTL;DRDiscoverable algorithms in C++

Searching  for algorithms based on the signatures of the transformations they can apply to data is invaluable.

For example, this link demonstrates a search engine used to discover all the available algorithms in Haskell for transformation given a signature "(int, [a]) -> [a]".

In C++, one library offers such a facility : FunctionalPlus.  Access its API search page and enter this in the search box:

(int, [a]) -> [a]

... and you will find many useful algorithms based on this signature (drop, repeat, stride, drop_idx, take_cyclic, partial_sort, etc, etc.).

I wish more libraries would follow this idea, since reasoning about values and their transformations is a powerful way to render the code more readable and correct at the same time.

A short C++ coding session using this technique

As an illustration, the video below shows a development session where a simple program is developed using such a search facility:

Links to solutions on Compiler Explorer:
Version with named variables: https://godbolt.org/z/YnK4bj
Version with a composed function: https://godbolt.org/z/n3Yh6s

Goal: no raw loop

Sean Parent said:

If you want to improve the code quality in your organization, replace all of your coding guidelines with one goal: no raw loop

(See C++ Seasoning video at 8'44")

In his mind, a "goal" shall not be thought as a "one must" or a "one must not",
but rather as a target you set out to follow to as much as possible.

In this context, having a search tool that helps your team to find the needed algorithms in order to avoid raw loops is invaluable IMHO. The previous video is a demonstration centered on this topic.

An old programing pearl

This  video is based on famous problem that was posed to Donald Knuth in 1986:

Given a text file and an integer k, print the k most common words in the file (and the number of their occurrences) in decreasing frequency.

Donald Knuth proposed a very advanced solution, demonstrating his style of “Literate Programming” through the WEB system. In his solution, he introduced innovative data structures (hash tries, etc.).  His solution was however quite lengthy, and limited to text documents: it was not so easy to turn it into a solution that could be adapted to similar problems.

In his review of Knuth's solution, Doug Mcllroy acknowledges the brilliance of the solution, and the elegance of the WEB system for literate programming. However, he proposed an alternate solution in 6 lines using standard Unix utilities:

Discoverable algorithms in C++
c

For those interested in the original discussion, refer to a pdf of the original article.

The unix shell solution is surprisingly elegant, as it solves the problem in simple and composable transformations. However, it can also be a little intimidating, and one might wonder "am I supposed to learn all those cryptic commands (sed, uniq, tr, etc.) and their arguments by heart?

The same is true for C++: how do we find the equivalent algorithms and transformations,that would be needed in order to reproduce such an elegant solution?

Discoverable algorithms  and transformations

Identifying an algorithm's signature

Let's examine one of those shell transformations: "uniq -c": it will replace each sequence of consecutive identical lines with one line that gives i) the number of lines and ii) the content of the line. In C++ terms, it could have the following signature:

vector < pair <size_t, string> > uniq_c(const vector<string>& v) { ... }

In more generic terms we could look for an algorithm with the following signature:

template<typename T>
vector< pair<size_t, T> > uniq_c(const vector<T>& v) { ... }

And in a more language agnostic way, we would say that the type of the signature of "uniq_c" is:

[a] -> [ (int, a) ]

i. e, given an array of type "a" (where a is a string for example), it returns an array of pair of type (number_of_occurrence, value of type a).

Searching for algorithms based on their signatures

In C++ , finding the good algorithm can sometimes be difficult. Knowing where to find the algorithm you need, and finding its name is all too often a barrier.
Jonathan Boccara has provided a helpful map, of which a picture can be found here, but apart from this, the search options are limited.
You are supposed to learn the different algorithms: this is a required part of the C++ background (and rightly so).

However, searching for algorithms based on their signature is surprisingly efficient. Let's for example think for one moment of all the algorithms that take as input an integer + an array, and return a modified array as an output.
Their signature is:

(int, [a]) -> [a]

Haskell offers a search engine, named Hoogle. With this tool, you would search for "int->[a]->[a]" (the signature is a bit different, since Haskell uses currying by default, which is beyond the scope of this post). And the results can be seen with this link.  

In C++, one library offers such a facility : FunctionalPlus. It's api search, is located at http://www.editgym.com/fplus-api-search/. Open the link and enter "(int, [a]) -> [a]" in the search box, and you will find the following list:

    (int,[a])->[a]
    
        drop : (Int, [a]) -> [a]
            Skip the first n elements of a sequence xs.
            If n > length(xs) an empty sequence is returned.
            drop(3, [0,1,2,3,4,5,6,7]) == [3,4,5,6,7]
            Also known as skip.
        
        take : (Int, [a]) -> [a]
            Return the first n elements of a sequence xs.
            In case n >= length(xs), xs is returned.
            take(3, [0,1,2,3,4,5,6,7]) == [0,1,2]
            take(10, [0,1,2]) == [0,1,2]
        
        repeat : (Int, [a]) -> [a]
            Create a sequence containing xs concatenated n times.
            repeat(3, [1, 2]) == [1, 2, 1, 2, 1, 2]
        
        stride : (Int, [a]) -> [a]
            Keeps every nth element.
            stride(3, [0,1,2,3,4,5,6,7]) == [0,3,6]
            Container stride(std::size_t step, const Container& xs)
        
        shuffle : (Int, [a]) -> [a]
            Returns a randomly shuffled version of xs.
            Example call: shuffle(std::mt19937::default_seed, xs);
            Example call: shuffle(std::random_device()(), xs);
        
        drop_idx : (Int, [a]) -> [a]
            Remove the element at a specific index from a sequence.
            drop_idx(2, [1,2,3,4,5,6,7]) == [1,2,4,5,6,7]
        
        drop_last : (Int, [a]) -> [a]
            Skip the last n elements of a sequence xs.
            If n > length(xs) an empty sequence is returned.
            drop_last(3, [0,1,2,3,4,5,6,7]) == [0,1,2,3,4]
        
        take_last : (Int, [a]) -> [a]
            Return the last n elements of a sequence xs.
            In case n >= length(xs), xs is returned.
            take_last(3, [0,1,2,3,4,5,6,7]) == [5,6,7]
            take_last(10, [0,1,2]) == [0,1,2]
        
        drop_exact : (Int, [a]) -> [a]
            Skip exactly the first n elements of a sequence xs.
            Unsafe! Crashes when xs is too short.
            drop_exact(3, [0,1,2,3,4,5,6,7]) == [3,4,5,6,7]
            drop_exact(10, [0,1,2,3,4,5,6,7]) == crash
        
        take_exact : (Int, [a]) -> [a]
            Return exactly the first n elements of a sequence xs.
            Unsafe! Crashes then sequence is too short.
            take_exact(3, [0,1,2,3,4,5,6,7]) == [0,1,2]
            take_exact(10, [0,1,2]) == crash
        
        take_cyclic : (Int, [a]) -> [a]
            Takes n elements from a sequence considering it as cyclic.
            take_cyclic(5, [0,1,2,3]) == [0,1,2,3,0]
            take_cyclic(7, [0,1,2,3]) == [0,1,2,3,0,1,2]
            take_cyclic(7, [0,1]) == [0,1,0,1,0,1,0]
            take_cyclic(2, [0,1,2,3]) == [0,1]
            take_cyclic(3, [0]) == [0,0,0]
            take_cyclic(3, []) == crash!
            Also known as take_wrap.
            xs must be non-empty.
        
        partial_sort : (Int, [a]) -> [a]
            Partially sort a sequence in ascending order using std::less.
            Returns only the sorted segment.
        
        replicate_elems : (Int, [a]) -> [a]
            Replicate every element n times, concatenate the result.
            replicate_elems(3, [1,2]) == [1, 1, 1, 2, 2, 2]
            Container replicate_elems(std::size_t n, const Container& xs)

A fast and elegant to search for algorithms and transformation!

Re-discovering RLE (run-length-encode)

Let's go back to "uniq -c".  If we go back to Fplus's search engine, and search for
[a] -> [ (int, a) ]
we discover the following functions.

    [a] -> [(Int, a)]
    
    enumerate : [a] -> [(Int, a)]
        Attach its index to every element of a sequence.
        enumerate([6,4,7,6]) == [(0, 6), (1, 4), (2, 7), (3, 6)]
    
    run_length_encode : [a] -> [(Int, a)]
        run_length_encode([1,2,2,2,2,3,3,2)) == [(1,1),(4,2),(2,3),(1,2)]


And, that's it!
Run length encoding is exactly what "uniq -c" is doing. We did not know the name of the algorithm, but the search engine geared us in the good direction.

I wish other libraries would follow this idea of being "searchable by signature".

Composing algorithms

Composing algorithms is a powerful way to develop new features, and to be more certain of the correctness of your program.

For comparison, the shell script:

tr -cs A-Za-z '\n' |  # 1 word per line
tr A-Z a-z |          # lowercase
sort |                # sort words (with possible repetitions)
uniq -c |             # group identical words and keep and count per group
sort -rn |            # numerical sort, inverted
sed $1q               # Display the n first lines

becomes, when translated to C++, using similar transformations:

std::function<string(string)> make_word_stats_processor(size_t nb_results)
{
  return fplus::compose(
      fplus::fwd::split_words(false)
    , fplus::fwd::transform(fplus::to_lower_case<string>) 
    , fplus::sort<std::vector<std::string>>
    , fplus::run_length_encode<std::vector<string>>
    , fplus::fwd::sort_by(greater<pair<size_t, string>>())
    , fplus::fwd::transform(show_word_count)
    , fplus::fwd::take(nb_results)
    , fplus::fwd::join(std::string("\n"))
  );
}

I'll be brutally honest about it: when writing such code, you will inevitably make type errors which the C++ compiler will "reward" with cryptic template error messages.  The first attempts might be painful.
However, the final code is very readable IMHO, and most of the time, a code that compiles will be correct at the first run!
Moreover, parallelization is then almost free (see fplus::transform_parallely for example).

Using pure higher order functions: an example with "interact"

fplus::interact enables to transform a string->string function into a complete stdin/stdout program. It is thus a higher order function that takes a function as parameter, and returns another  function.

Here is its signature:

interact : (String -> String) -> Io ()

Takes a function F of type (String -> String)
and returns a function that
reads the entire input from standard input,
passes it through the given function,
and writes the result to standard output.

The Io() at the end of the signature signals that the returned function will be able, when called, to perform side effects (e.g read from stdin and write to stdout).

However, fplus::interact is in itself a pure function. It will not perform the side effect by itself, since you have to run the returned function in order to perform the side effect. This way, this function remains pure and composable.

]]>
<![CDATA[REPL in C++: types to the rescue]]>https://code-ballads.net/repl-in-c-types-to-the-rescue/5c6706ca4fc4df00013ccc67Fri, 15 Feb 2019 18:45:38 GMTThis post is a follow-up to my hands-on session article about C++ REPL.

Being able to  display readable types and content for your variables and functions can greatly improve the user experience inside a C++ REPL.

This article is very short, so that you can jump to the short (2 minutes) demonstration video below. It is based on CleanType, a C++ header-only library whose intent is to get readable types and content.

For those in a hurry, you can skip to the video transcript at the end of this page.

Some links before concluding this article:

  • The demo code for this REPL demo is available here
  • For those who were interested in the jupyter notebook C++ REPL environment, you can also try it inside jupyter notebook (beware, this may require a minute or two to load, mybinder.org is sometimes sluggish)
  • For those who prefer a demo in a more standard C++ environment, here is a simple demo, which you can also try interactively on gitpod (registration required)

Video Transcript

Note: Here is link to the same transcript as a gist, with nicer colors.


// REPL in C++: display readable types and
// variable contents.

// This demo uses cling, a fully compliant C++14 REPL,
// and asciinema, a terminal session recorder.
// It is based on CleanType (a C++ type introspection
// library)
// You can pause at any time, and copy-paste samples from it.

#include <cleantype/cleantype.hpp>

// The dumbest logger in the west...
#define LOG(...) std::cout << __VA_ARGS__ << "\n";

// First, let's define a variable for demonstration purpose
std::set<std::string> my_set { "Hello", "There"};

// let's ask CleanType to give us the type of "my_set"
// cleantype::full will return the *full* type info
LOG(  cleantype::full(my_set)  );
--> std::set<std::__cxx11::basic_string<char>, std::less<std::__cxx11::basic_string<char>>, std::allocator<std::__cxx11::basic_string<char>>> &


// Ouch, that was barely readable!
// cleantype::clean will return a *readable* type
LOG(  cleantype::clean(my_set) );
--> std::set<std::string> &

// Let's now show the content of "my_set" together
// with its type
LOG(  cleantype::show_details(my_set) );
--> std::set<std::string> & = [Hello, There]


// Yes, but what about lambdas? Could you guess
// the signature of the lambda below?
auto lambda_example = []() {
    // when C++ meets js...
    return +!!"";
    // See https://blog.knatten.org/2018/10/12/1662
};

// cleantype::lambda_clean returns the signature of lambda functions
LOG(  cleantype::lambda_clean(lambda_example) );
--> lambda: () -> int

// Ok, maybe this was too easy.
// Let's try with a generic lambda!
auto add = [](auto a, auto b) {
    return a + b;
};

// Now, can we see its signature?
// Yes, we just need to specify the args types.
LOG(  cleantype::lambda_clean<std::string, char>(add)  );
--> lambda: (std::string, char) -> std::string



// Can CleanType understand some more complex libraries
// like range-v3 where most variables, functions
// and lambdas are of type "auto"?
// Well...    yes!

#include <range/v3/all.hpp>

using namespace ranges;

auto square_yield_fn(int x) {
  return ranges::yield(x * x);
}
auto squares_view = view::for_each(view::ints(1), square_yield_fn);

// What is the type of squares_view?
// Let's see...
LOG( cleantype::clean(squares_view)  );
--> ranges::v3::join_view<ranges::v3::transform_view<ranges::v3::iota_view<int, void>, ranges::v3::single_view<int>(*)(int)>, void> &

// Let's make it more complex yet:
auto squares_take_10 = squares_view | view::take(10);

// As you will see below, CleanType can indent
// the types when they get more complex!

LOG(  cleantype::clean(squares_take_10)  );
--> ranges::v3::detail::take_exactly_view_<
    ranges::v3::join_view<
        ranges::v3::transform_view<
            ranges::v3::iota_view<
                int,
                void
            >,
            ranges::v3::single_view<
                int
            > (*)(int)
        >,
        void
    >,
    false
> &



// Thanks for watching!

]]>
<![CDATA[CleanType - Readable and consistent C++ type introspection - Compiler Decipherer]]>https://code-ballads.net/cleantype/5c4328a4dab1fe0001fd54b4Tue, 22 Jan 2019 19:42:23 GMTCleanType  is a small C++14 header only library which offer readable type names, with a consistent naming scheme across compilers, at run-time and compile-time. It can also output the signature of lambda functions, and the result type of any auto function.

The included tool (ct_compiler_decipher) simplifies the template noise in your compiler output: just pipe ("|") your build tool to it.CleanType - Readable and consistent C++ type introspection - Compiler DeciphererCleanType - Readable and consistent C++ type introspection - Compiler Decipherer

This project started as a simple "what if" project: I wanted to be able to get more information about the types hidden behind auto variables, lambdas, etc; and I wanted to be able to get this information interactively (e.g. inside a C++ REPL, or from the compiler output).

Features

If you are interested in this project, stop reading here! Instead, go to the full manual which is much more complete and interesting than this introductory article. This manual is also available in a fully interactive version (beware, it may require about 1 minute to load; but then you will be able to run the code live from your browser!)
  • Readable type names
    e.g std::string  
    instead of std::basic_string<char, std::allocator<char>>
  • Readable type names in the compiler error output
    Because no one likes to be punished with template gibberish when trying to correct an error.
  • Identify the auto return type of functions and the signature of lambdas
    Because it is a great way to understand what's going on in the code.
  • Identify types in the compiler output
    Because sometimes we are lost in a forest of auto return types; and we would like the compiler to tell us what he knows (and is hiding from us!)
  • Compile time constexpr type names

Highlights

Below are some non interactive highlights for the impatient reader.

Readable types and signatures

Suppose you have a lambda (cache_int_strings) that will create a sort of cache between the n first integers and their string representation (natural representation, and roman number representation). Using cleantype, you can get its signature like this:

std::cout << cleantype::lambda_clean(cache_int_strings);
==> lamda: (int) -> std::map<int, std::array<std::string, 2>>

or, depending on the indent limit, which is configurable:

lambda: (int) -> std::map< // lambda signature
    int,                   // cleantype can indent the types
    std::array<
        std::string,  // note: cleantype will decipher the type
        2             // (i.e basic_string<char,......>> in this case)
    >
>

You can also print the type and content of any container

auto five_numbers = make_cache_int_strings(5);
std::cout << CT_show_details(five_numbers);

will output

[std::map<
    int,
    std::array<
        std::string,
        2
    >
>] five_numbers = [(1, ["1", "I"]), (2, ["2", "II"]), (3, ["3", "III"]), (4, ["4", "IV"]), (5, ["5", "V"])]

Notes: the full source for this demo is available here. Of course, CleanType handles more than just lambdas, and is able to output any type.

Decipher the compiler output

Suppose you have an error and you are being punished by the compiler. The tool ct_compiler_decipher   can make your life easier. Just pipe your build command line to it:

> clang++ --std=c++14 -c code.cpp 2>&1 | ct_compiler_decipher
code.cpp:10:42: error: invalid operands to binary expression ('std::map<std::string, int> ' and 'int')
    auto add_one = [](auto x) { return x + 1; };
                                       ~ ^ ~

Here, 'std::map<std::__cxx11::basic_string<char>,.... >' was deciphered to std::map<std::string, int>

Miscellaneous remarks and questions

With this project, I am experiencing with a new interactive way of presenting a project manual. I decided not to use a static documentation web pages since the manual provides an auto-generated table of content. Then, I also decided to binder in order to turn this manual into a fully interactive manual (beware, it may require about 1 minute to load). What is your opinion about this? If you are interested in this interactive way of development, you can also read my article about it.

Also I am gathering input concerning the time to load binder: in my experience the load time can vary between 10 seconds and 3 minutes! I do hope that binder gains traction and becomes faster in the near future. What was your mileage?
Note: if your page seems to be stuck during loading, try to reload it after 1 minute (and meanwhile, you can read the manual in the preview).

I do not claim that this library is 100% foolproof: it is still in its infancy, so that you may expect some bugs. However, I still think it is usable and useful.

I did some efforts in order to get readable representations for most of the STL types, but I certainly forgot some aspects. Cleantype is highly configurable, so that I think it could be adapted to most users needs, as long as they are not torturing the compiler with highly complex templates. Please do try the interactive demos: do you see some types for which some additional deciphering would be required?

As you can see, this library is standalone and header-only. It does not depend on clang libtooling. This is a choice because I wanted it to be as simple as possible to adopt, and as portable as possible.
Of course, this means that the compilation time may increase. So, you may as well consider this library as a drop-in solution: just #include "cleantype.hpp" whenever you need it in your cpp file (or inside your C++ REPL), and then remove it once it helped you find the type you were looking for.

Is it worthwhile to try to define a "normalized" string version of a type? In my opinion, the "east-const" vs "west-const" is just the tip of the iceberg. It is a sign that more established "spelling conventions" would be needed, as far as the types are concerned. They should not be enforced by the compiler, but they should exist someway .
Sadly, the C++ ecosystem is heavily fragmented between different cultures, compilers and toolchains. Humans, compilers, libc implementations : everyone disagrees on what should be the normalized string representation of a type. See an interactive analysis here: typesetting : the east vs west pointless holy war?

]]>
<![CDATA[REPL (Read-Eval-Print-Loop) in C++: hands-on session]]>https://code-ballads.net/read-eval-print-loop-repl-in-c/5c113b7786ce2e00013f420eWed, 12 Dec 2018 16:51:45 GMT

An efficient way to prototype  C++ applications & research work and to write demonstrations or teaching material using C++

A Read-Eval-Print-Loop (REPL) enables to leverage very rapid and robust application development, prototyping and testing. This kind of development environment originates from the early days of functional programming (Lisp machines and the like), and is common in functional and scripting languages.

As a compiled language, C++ was out of the loop for a long time.

Enters CLING

Cling realizes the read-eval-print loop (REPL) concept for the C++ language. Thus, you can gain in speed of development while the compiler (clang) still checks your code and guarantees a native speed of execution.

Hands-on demonstrations

This article demonstrates how easy and useful it can sometimes be to work in this kind of environment in C++. This is especially useful in order to develop with a functional approach (such as with the range-v3 library), and for research and/or training applications.

This article is voluntarily very short, so that you can jump to the hands-on demonstrations. You will be able to use the a C++ REPL online, without even having to install anything.

Go to the demonstration notebooks

(opens in a new window)

About the tools that were used to write these notebooks

These notebooks  were written using REPL tools, namely jupyter notebook,  xeus cling and of course cling. More info in the notebooks themselves.

]]>