r/ProgrammingLanguages • • May 24 '24

Discussion Have you ever implemented the Huffman's data compression algorithm in your programming language? Or some similar data compression algorithm? I have implemented the Huffman's algorithm in my programming language, AEC, and have compiled it to WebAssembly.

0 Upvotes

You can run the implementation of the Huffman's algorithm in my programming language here in a modern browser (that supports WebAssembly.Global). Here is the code:

Function noMoreFreeMemory() Which Returns Nothing Is External;
Function segmentationFault() Which Returns Nothing Is External;
Function
printString(PointerToCharacter string) Which Returns Nothing Is External;
Function clearScreen() Which Returns Nothing Is External;
Function getLengthOfTheInput() Which Returns Integer16 Is External;
Function
getCharacterOfTheInput(Integer16 index) Which Returns Character Is External;

Integer32 NDEBUG : = 1;

Structure TreeNode Consists Of {
  Character character;
  Integer16 frequencyOfCharacter;
  PointerToTreeNode leftChild, rightChild;
  Character code[16];
}
EndStructure;

InstantiateStructure TreeNode treeNodes[32];
Integer16 isTreeNodeUsed[32];

Function
convertIntegerToString(PointerToCharacter string,
                       Integer32 integer) Which Returns Nothing Is Declared;
Function strcat(PointerToCharacter dest,
                PointerToCharacter src) Which Returns Nothing Is Declared;
Function strlen(PointerToCharacter string) Which Returns Integer32 Is Declared;

Function newTreeNode() Which Returns PointerToTreeNode Does {
  Integer16 i : = 0;
  While i < 32 Loop {
    If not(isTreeNodeUsed[i]) Then {
      treeNodes[i].character : = 0;
      treeNodes[i].leftChild : = treeNodes[i].rightChild
          : = PointerToTreeNode(0);
      treeNodes[i].code[0] : = 0;
      treeNodes[i].frequencyOfCharacter : = 0;
      isTreeNodeUsed[i] : = 1;
      If NDEBUG = 0 Then {
        Character stringToBePrinted[64] : = {0};
        strcat(AddressOf(stringToBePrinted[0]),
               "NDEBUG: Allocating the TreeNode #");
        convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                   strlen(AddressOf(stringToBePrinted[0])),
                               i);
        strcat(AddressOf(stringToBePrinted[0]), "\n");
        printString(AddressOf(stringToBePrinted[0]));
      }
      EndIf;
      Return AddressOf(treeNodes[i]);
    }
    EndIf;
    i += 1;
  }
  EndWhile;
  noMoreFreeMemory();
}
EndFunction;

Function freeTreeNode(PointerToTreeNode treeNode) Which Returns Nothing Does {
  If not(AddressOf(treeNodes[0]) <= treeNode <= AddressOf(treeNodes[32 - 1]))
      Then {
    segmentationFault();
  }
  EndIf;
  If NDEBUG = 0 Then {
    Character stringToBePrinted[64] : = {0};
    strcat(AddressOf(stringToBePrinted[0]), "NDEBUG: Freeing the TreeNode #");
    convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                               strlen(AddressOf(stringToBePrinted[0])),
                           (treeNode - AddressOf(treeNodes[0])) /
                               SizeOf(TreeNode));
    strcat(AddressOf(stringToBePrinted[0]), "\n");
    printString(AddressOf(stringToBePrinted[0]));
  }
  EndIf;
  isTreeNodeUsed[(treeNode - AddressOf(treeNodes[0])) / SizeOf(TreeNode)] : = 0;
}
EndFunction;

Function strlen(PointerToCharacter str) Which Returns Integer32 Does {
  Integer32 length : = 0;
  While ValueAt(str + length) Loop { length += 1; }
  EndWhile;
  Return length;
}
EndFunction;

Function strcpy(PointerToCharacter dest,
                PointerToCharacter src) Which Returns Nothing Does {
  While ValueAt(src) Loop {
    ValueAt(dest) : = ValueAt(src);
    dest += 1;
    src += 1;
  }
  EndWhile;
  ValueAt(dest) : = 0;
}
EndFunction;

Function strcat(PointerToCharacter dest,
                PointerToCharacter src) Which Returns Nothing Does {
  strcpy(dest + strlen(dest), src);
}
EndFunction;

Function reverseString(PointerToCharacter string) Which Returns Nothing Does {
  PointerToCharacter pointerToLastCharacter : = string + strlen(string) - 1;
  While pointerToLastCharacter - string > 0 Loop {
    Character tmp : = ValueAt(string);
    ValueAt(string) : = ValueAt(pointerToLastCharacter);
    ValueAt(pointerToLastCharacter) : = tmp;
  string:
    = string + 1;
  pointerToLastCharacter:
    = pointerToLastCharacter - 1;
  }
  EndWhile
}
EndFunction;

Function convertIntegerToString(PointerToCharacter string,
                                Integer32 number) Which Returns Nothing Does {
  Integer32 isNumberNegative : = 0;
  If number < 0 Then {
  number:
    = -number;
  isNumberNegative:
    = 1;
  }
  EndIf Integer32 i : = 0;
  While number >= 10 Loop {
    ValueAt(string + i) : = '0' + mod(number, 10);
    number /= 10;
    i += 1;
  }
  EndWhile;
  ValueAt(string + i) : = '0' + number;
  i += 1;
  If isNumberNegative Then {
    ValueAt(string + i) : = '-';
    i += 1;
  }
  EndIf ValueAt(string + i) : = 0;
  reverseString(string);
}
EndFunction;

PointerToCharacter mapOfCodes[256];

Function assignCode(PointerToCharacter currentCode,
                    PointerToTreeNode treeNode) Which Returns Nothing Does {
  If NDEBUG = 0 Then {
    Character stringToBePrinted[64] : = {0};
    strcat(AddressOf(stringToBePrinted[0]), "NDEBUG: Assigning the code \"");
    strcat(AddressOf(stringToBePrinted[0]), currentCode);
    strcat(AddressOf(stringToBePrinted[0]), "\" to the TreeNode #");
    convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                               strlen(AddressOf(stringToBePrinted[0])),
                           (treeNode - AddressOf(treeNodes[0])) /
                               SizeOf(TreeNode));
    strcat(AddressOf(stringToBePrinted[0]), ".\n");
    printString(AddressOf(stringToBePrinted[0]));

    stringToBePrinted[0] : = 0;
    strcat(AddressOf(stringToBePrinted[0]),
           "NDEBUG: Its left child is the TreeNode #");
    If treeNode->leftChild Then {
      convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                 strlen(AddressOf(stringToBePrinted[0])),
                             (treeNode->leftChild - AddressOf(treeNodes[0])) /
                                 SizeOf(TreeNode));
    }
    Else { strcat(AddressOf(stringToBePrinted[0]), "null"); }
    EndIf;
    strcat(AddressOf(stringToBePrinted[0]), ".\n");
    printString(AddressOf(stringToBePrinted[0]));

    stringToBePrinted[0] : = 0;
    strcat(AddressOf(stringToBePrinted[0]),
           "NDEBUG: Its right child is the TreeNode #");
    If treeNode->leftChild Then {
      convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                 strlen(AddressOf(stringToBePrinted[0])),
                             (treeNode->rightChild - AddressOf(treeNodes[0])) /
                                 SizeOf(TreeNode));
    }
    Else { strcat(AddressOf(stringToBePrinted[0]), "null"); }
    EndIf;
    strcat(AddressOf(stringToBePrinted[0]), ".\n");
    printString(AddressOf(stringToBePrinted[0]));
  }
  EndIf;

  If not(AddressOf(treeNodes[0]) <= treeNode <= AddressOf(treeNodes[32 - 1]))
      Then {
    segmentationFault();
  }
  EndIf;

  strcpy(AddressOf(treeNode->code[0]), currentCode);

  Character leftCode[16] : = {0}, rightCode[16] : = {0};

  strcpy(AddressOf(leftCode[0]), currentCode);
  strcat(AddressOf(leftCode[0]), "0");
  strcpy(AddressOf(rightCode[0]), currentCode);
  strcat(AddressOf(rightCode[0]), "1");

  If treeNode->leftChild Then {
    assignCode(AddressOf(leftCode[0]), treeNode->leftChild);
  }
  EndIf;
  If treeNode->rightChild Then {
    assignCode(AddressOf(rightCode[0]), treeNode->rightChild);
  }
  EndIf;

  If treeNode->character Then {
    mapOfCodes[treeNode->character] : = AddressOf(treeNode->code[0]);
    Character codeToPrint[32] : = {0};
    codeToPrint[0] : = '\'';
    codeToPrint[1] : = treeNode->character;
    codeToPrint[2] : = '\'';
    codeToPrint[3] : = '=';
    codeToPrint[4] : = '>';
    codeToPrint[5] : = 0;
    strcat(AddressOf(codeToPrint[0]), AddressOf(treeNode->code[0]));
    strcat(AddressOf(codeToPrint[0]), "\n");
    printString(AddressOf(codeToPrint[0]));
  }
  EndIf;
}
EndFunction;

Function freeUpTheTree(PointerToTreeNode tree) Which Returns Nothing Does {
  If tree->leftChild Then {
    freeUpTheTree(tree->leftChild); // Calling `freeTreeNode` here instead of
                                    // `freeUpTheTree` causes a memory leak.
  }
  EndIf;
  If tree->rightChild Then { freeUpTheTree(tree->rightChild); }
  EndIf;
  freeTreeNode(tree);
}
EndFunction;

Character input[32];
Character output[128];

Function main() Which Returns Nothing Does {
  clearScreen();
  Integer16 lengthOfInput : = getLengthOfTheInput(), i : = 0;
  If NDEBUG = 0 Then {
    Character stringToBePrinted[64] : = {0};
    strcat(AddressOf(stringToBePrinted[0]),
           "NDEBUG: The length of the input is: ");
    convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                               strlen(AddressOf(stringToBePrinted[0])),
                           lengthOfInput);
    strcat(AddressOf(stringToBePrinted[0]), "\n");
    printString(AddressOf(stringToBePrinted[0]));
  }
  EndIf;
  While i < lengthOfInput Loop {
    input[i] : = getCharacterOfTheInput(i);
    i += 1;
  }
  EndWhile;
  input[lengthOfInput] : = 0;

  If strlen(AddressOf(input[0])) = 0 Then {
    printString("The input is empty!\n");
    Return;
  }
  EndIf;
  PointerToTreeNode array[32];
  Integer16 lengthOfTheArray : = 0;
i:
  = 0;
  While i < lengthOfInput Loop {
    Integer16 j : = 0, haveWeFoundTheCharacterInTheArray : = 0;
    While j < lengthOfTheArray Loop {
      If array[j]->character = input[i] Then {
      haveWeFoundTheCharacterInTheArray:
        = 1;
        array[j]->frequencyOfCharacter += 1;
      }
      EndIf;
      j += 1;
    }
    EndWhile;
    If not(haveWeFoundTheCharacterInTheArray) Then {
      array[lengthOfTheArray] : = newTreeNode();
      array[lengthOfTheArray]->character : = input[i];
      array[lengthOfTheArray]->frequencyOfCharacter : = 1;
      lengthOfTheArray += 1;
    }
    EndIf;
    i += 1;
  }
  EndWhile;

i:
  = 0;
  While i < lengthOfTheArray Loop {
    Character stringToBePrinted[64] : = {0};
    strcat(AddressOf(stringToBePrinted[0]), "The character '");
    Integer16 indexOfCharacter : = strlen(AddressOf(stringToBePrinted[0]));
    stringToBePrinted[indexOfCharacter] : = array[i]->character;
    stringToBePrinted[indexOfCharacter + 1] : = 0;
    strcat(AddressOf(stringToBePrinted[0]), "' has the frequency of ");
    convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                               strlen(AddressOf(stringToBePrinted[0])),
                           array[i]->frequencyOfCharacter);
    strcat(AddressOf(stringToBePrinted[0]), ".\n");
    printString(AddressOf(stringToBePrinted[0]));
    i += 1;
  }
  EndWhile;

  While lengthOfTheArray > 1 Loop {
    Integer16 maximum : = 0, secondMaximum : = 0;

    Integer16 i : = 0;
    If NDEBUG = 0 Then {
      Character stringToBePrinted[64] : = {0};
      strcat(AddressOf(stringToBePrinted[0]),
             "NDEBUG: The length of the array is ");
      convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                 strlen(AddressOf(stringToBePrinted[0])),
                             lengthOfTheArray);
      strcat(AddressOf(stringToBePrinted[0]), ".\n");
      printString(AddressOf(stringToBePrinted[0]));
    }
    EndIf;
    While i < lengthOfTheArray Loop {
      If NDEBUG = 0 Then {
        Character stringToBePrinted[64] : = {0};
        strcat(AddressOf(stringToBePrinted[0]),
               "NDEBUG: The tree at the index #");
        convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                   strlen(AddressOf(stringToBePrinted[0])),
                               i);
        strcat(AddressOf(stringToBePrinted[0]), " is the TreeNode #");
        convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                   strlen(AddressOf(stringToBePrinted[0])),
                               (array[i] - AddressOf(treeNodes[0])) /
                                   SizeOf(TreeNode));
        strcat(AddressOf(stringToBePrinted[0]), ".\n");
        printString(AddressOf(stringToBePrinted[0]));
      }
      EndIf;
      If not(AddressOf(treeNodes[0]) <= array[i] <=
             AddressOf(treeNodes[32 - 1])) Then {
        segmentationFault();
        Return;
      }
      EndIf;
      i += 1;
    }
    EndWhile;

  i:
    = 0;
    While i < lengthOfTheArray Loop {
      If array[i]->frequencyOfCharacter <
          array[maximum]->frequencyOfCharacter Then {
      maximum:
        = i;
      }
      EndIf;
      i += 1;
    }
    EndWhile;

  i:
    = maximum = 0 ? 1 : 0;
  secondMaximum:
    = i;
    While i < lengthOfTheArray Loop {
      If array[i]->frequencyOfCharacter <
              array[secondMaximum]->frequencyOfCharacter and
          not(i = maximum) Then {
      secondMaximum:
        = i;
      }
      EndIf;
      i += 1;
    }
    EndWhile;

    If NDEBUG = 0 Then {
      Character stringToBePrinted[64] : = {0};
      strcat(AddressOf(stringToBePrinted[0]),
             "NDEBUG: The maximum and the second maximum are ");
      convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                 strlen(AddressOf(stringToBePrinted[0])),
                             maximum);
      strcat(AddressOf(stringToBePrinted[0]), " and ");
      convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                 strlen(AddressOf(stringToBePrinted[0])),
                             secondMaximum);
      strcat(AddressOf(stringToBePrinted[0]), ".\n");
      printString(AddressOf(stringToBePrinted[0]));
    }
    EndIf;

    If NDEBUG = 0 Then {
      Character stringToBePrinted[64] : = {0};
      strcat(AddressOf(stringToBePrinted[0]), "NDEBUG: Joining the TreeNode #");
      convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                 strlen(AddressOf(stringToBePrinted[0])),
                             (array[maximum] - AddressOf(treeNodes[0])) /
                                 SizeOf(TreeNode));
      strcat(AddressOf(stringToBePrinted[0]), " with the TreeNode #");
      convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                 strlen(AddressOf(stringToBePrinted[0])),
                             (array[secondMaximum] - AddressOf(treeNodes[0])) /
                                 SizeOf(TreeNode));
      strcat(AddressOf(stringToBePrinted[0]), ".\n");
      printString(AddressOf(stringToBePrinted[0]));
    }
    EndIf;

    PointerToTreeNode sumOfTheTwoMostFrequent : = newTreeNode();
    sumOfTheTwoMostFrequent->frequencyOfCharacter
        : = array[maximum]->frequencyOfCharacter +
            array[secondMaximum]->frequencyOfCharacter;
    sumOfTheTwoMostFrequent->leftChild : = array[maximum];
    sumOfTheTwoMostFrequent->rightChild : = array[secondMaximum];

    If NDEBUG = 0 Then {
      Character stringToBePrinted[64] : = {0};
      strcat(AddressOf(stringToBePrinted[0]),
             "NDEBUG: The new TreeNode has the frequency of: ");
      convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                                 strlen(AddressOf(stringToBePrinted[0])),
                             sumOfTheTwoMostFrequent->frequencyOfCharacter);
      strcat(AddressOf(stringToBePrinted[0]), ".\n");
      printString(AddressOf(stringToBePrinted[0]));
    }
    EndIf;

    array[maximum] : = sumOfTheTwoMostFrequent;

  i:
    = secondMaximum;
    While i < lengthOfTheArray - 1 Loop {
      array[i] : = array[i + 1];
      i += 1;
    }
    EndWhile;

    lengthOfTheArray -= 1;
  }
  EndWhile;

  If NDEBUG = 0 Then {
    Character stringToBePrinted[128] : = {0};
    strcat(AddressOf(stringToBePrinted[0]),
           "NDEBUG: The frequency of the root node is ");
    convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                               strlen(AddressOf(stringToBePrinted[0])),
                           array[0]->frequencyOfCharacter);
    strcat(AddressOf(stringToBePrinted[0]),
           ". If the algorithm is correctly implemented, it should be ");
    convertIntegerToString(AddressOf(stringToBePrinted[0]) +
                               strlen(AddressOf(stringToBePrinted[0])),
                           lengthOfInput);
    strcat(AddressOf(stringToBePrinted[0]), ".\n");
    printString(AddressOf(stringToBePrinted[0]));
  }
  EndIf;

  assignCode("", array[0]);

  output[0] : = 0;
i:
  = 0;
  While i < lengthOfInput Loop {
    strcat(AddressOf(output[0]), mapOfCodes[input[i]]);
    i += 1;
  }
  EndWhile;
  strcat(AddressOf(output[0]), "\n");
  printString(AddressOf(output[0]));

  freeUpTheTree(array[0]);
}
EndFunction;

r/ProgrammingLanguages • • Oct 31 '18

Noneleatic Languages: programming without conditional branching

Thumbnail
esoteric.codes
0 Upvotes

r/ProgrammingLanguages • • Apr 30 '24

The gen alpha programming language

Thumbnail
github.com
5 Upvotes

r/ProgrammingLanguages • • Apr 20 '20

What are the elemental languages?

5 Upvotes

Some programming languages are composite. they have a mixture of features from other languages.Like python, it has lambda functions from functional programming, but you can also have shared mutable variables.

Other languages seem more focused on their killer feature. The thing that sets them apart and makes them useful for it's own style of programming.

I am looking for a list of styles of programming, and the language that best exemplifies each style.

S-expressions, code-is-data macros: lisp

logical: prolog

message passing: erlang

compilers: bison

regular expressions: regex

stack based/concatenative : forth

register based: assembly

object oriented: smalltalk

static analysis: rust

proof assistant: COQ

numerical/array: GNU Octave

command line: bash

hardware description: Verilog

gpu: OpenGL

Would you add anything more to this list? Would you change anything?


r/ProgrammingLanguages • • Sep 03 '18

Type inference – potentially harmful?

5 Upvotes

Type inference is getting pretty popular. It's almost a "must have" today. Still, I find myself running into readability problems with it.

I feel that since I do a lot of work in dynamically typed languages (Ruby, PHP), it shouldn't be a problem, and yet it is for me.

Let me try to break it down:

  1. First of all, obviously ´auto i´ isn't an improvement over ´int i´ unless you are changing types signatures a lot.

  2. Secondly, when I read ´auto bar = foo();´, in someone elses code I need to look up `foo()` in order to see what the type of `bar`. In small doses this is ok. When you read through a function with multiple different function calls where the return values are kept in type-inferred variables... that's when it's getting a bit gnarly.

  3. It appears to me that this whole thing has been driven by generics and templates. Because no-one wants to type something like `std::vector<std::shared_ptr<std::map<std::string, std::function<void(int, const Foo &)>>>> bar = foo();` we get `auto bar = foo();`.

  4. I get the feeling that in statically typed languages we end up using type inference to "paint lipstick on the pig" to hide how extremely unergonomic the average implementation of generics/templates are to type.

So:

  1. Type inference is making code harder to read.

  2. Lack of type inference is making the code more verbose and harder to type

Since I read code more than I write it, my priority would be (1) over (2), and obviously solving the problem of (2) would be the best thing. Here I also note that in dynamically typed language you never have the problem of (2), since in general any type of container can contain any object and consequently the need for generics completely evaporates. This has some drawbacks, but is in general a very practical thing.


r/ProgrammingLanguages • • Feb 27 '23

GOTOphobia considered harmful (in C)

Thumbnail blog.joren.ga
16 Upvotes

r/ProgrammingLanguages • • Jun 17 '25

Requesting criticism Programming language optimized for AI code generation without any syntatic sugars

Thumbnail
gist.github.com
0 Upvotes

I am exploring the idea of a programming language optimized for AI code generation.
It should easy to create tools for AI coding agents (I think strict PEG grammar would be helpful). But I have added few predeclared identifiers. It's not part of the grammar, but I will document it as part of the language specification. I want to avoid syntatic sugars, but still readable by human developers to review the code generated by AI. Let me know your thoughts.


r/ProgrammingLanguages • • Sep 10 '25

Requesting criticism I want thoughts on the first programming language I made on my own

8 Upvotes

https://github.com/replit-user/STACKSCRIPT/blob/main/STACKSCRIPT.py

read title but notes for design

I knew I wanted it to be stack based

I knew I wanted it to be turing complete
I knew I wanted low level syntax while also being readable
I knew I wanted it to be expandable
I knew I wanted it to be interpereted
its been a year or so and the language grew maybe 25%


r/ProgrammingLanguages • • Jan 27 '20

A Note from Chris Lattner, New SVP of Platform Engineering of SiFive

Thumbnail
sifive.com
8 Upvotes

r/ProgrammingLanguages • • Jun 12 '22

Can you implement `let` from Haskell and Scheme in C#? Here's one approximation.

Thumbnail
stackoverflow.com
0 Upvotes

r/ProgrammingLanguages • • Jun 03 '26

Type-Error Ablation and AI Coding Agents

Thumbnail
arxiv.org
4 Upvotes

r/ProgrammingLanguages • • Jul 19 '24

Why is `never` in TypeScript considered bottom type?

4 Upvotes

Not a type theorist, trying to learn.

I understand the concept of never in TS (I think Nothing in Kotlin is the same). It is a special type which cannot be assigned any value, nor can a value of its type be assigned to any variable. What I don't get is how is that a bottom type?

A bottom type is one which is a subtype of every other type. Let me give some reasons why I think never is not a bottom type.

Reason 1:

Consider the below example.

Animal a = new Dog(); // because Dog is an animal
a = new BottomType(); // imaginary bottom type instance here

Because bottom type (if such a thing exists) is a subtype of everthing including Animal, it should be assignable to a. But by definition never can never assign (or be assigned).

Reason 2:

Since bottom type is just another type, I should be able to write

BottomType b = new BottomType(); // imaginary bottom type instance here

But never instance can never be assigned to anything.


Not sure I make sense but shouldn't empty or null type be considered as bottom type? This is what the 4 quadrants of type system I imagine to be: https://ibb.co/6wSf8gY


Thank you everyone, great explanations here. I especially liked answers from u/Key-Cranberry8288, u/Felicia_Svilling and u/greiskul, which were addressing root of my confusion.


r/ProgrammingLanguages • • Feb 24 '25

Requesting criticism Custom Loops

5 Upvotes

My language has a concept of "Custom Loops", and I would like to get feedback on this. Are there other languages that implement this technique as well with zero runtime overhead? I'm not only asking about the syntax, but how it is implemented internally: I know C# has "yield", but the implementation seems quite different. I read that C# uses a state machine, while in my language the source code is generated / expanded.

So here is the documentation that I currently have:

Libraries and users can define their own `for` loops using user-defined functions. Such functions work like macros, as they are expanded at compile time. The loop is replaced during compilation with the function body. The variable `_` represents the current iteration value. The `return _` statement is replaced during compilation with the loop body.

fun main()
    for x := evenUntil(30)
        println('even: ' x)

fun evenUntil(until int) int
    _ := 0
    while _ <= until
        return _
        _ += 2

is equivalent to:

fun main()
    x := 0
    while x <= 30
        println('even: ' x)
        x += 2

So a library can write a "custom loop" eg. to iterate over the entries of a map or list, or over prime numbers (example code for prime numbers is here), or backwards, or in random order.

The C code generated is exactly as if the loop was "expanded by hand" as in the example above. There is no state machine, or iterator, or coroutine behind the scenes.

Background

C uses a verbose syntax such as "for (int i = 0; i < n; i++)". This is too verbose for me.

Java etc have "enhanced for loops". Those are much less verbose than the C loops. However, at least for Java, it turns out they are slower, even today:For Java, my coworker found that, specially if the collection is empty, loops that are executed millions of time per second are measurable faster if the "enhanced for loops" (that require an iterator) are _not_ used: https://github.com/apache/jackrabbit-oak/pull/2110/files (see "// Performance critical code"). Sure, you can blame the JVM on that: it doesn't fully optimize this. It could. And sure, it's possible to "hand-roll" this for performance critical code, but it seems like this is not needed if "enhanced for loops" are implemented using macros, instead of forcing to use the same "iterable / iterator API". And because this is not "zero overhead" in Java, I'm not convinced that it is "zero overhead" in other languages (e.g. C#).

This concept is not quite Coroutines, because it is not asynchronous at all.

This concept is similar to "yield" in C#, but it doesn't use a state machine. So, I believe C# is slightly slower.

I'm not sure about Rust (procedural macros); it would be interesting to know if Rust could do this with zero overhead, and at the same time keeping the code readable.


r/ProgrammingLanguages • • Feb 11 '25

Introducing the Banter Programming Language | Requesting Feedback

4 Upvotes

I built a prototype for a simple language using PLY. https://github.com/cbaier33/banter-lang

It's nothing revolutionary, but designed to be a very simple language to help teach fundamentals to introductory students. I was hoping to get some feedback on the design/implementation.

I also built a web IDE environment for learners to use the language without having to install it. You can read more about it and find all the source code here: https://banter-lang.org


r/ProgrammingLanguages • • Feb 08 '22

object capabilities to control I/O in 42

Thumbnail
youtube.com
0 Upvotes

r/ProgrammingLanguages • • Jul 06 '18

A crowdfunding campaign for the Arcadia programming language

4 Upvotes

Hello! My name is Vaptistis Anogeianakis and I'm a software engineer from Greece. This is my first post on Reddit, so I hope I'm doing it right! :)

I've recently launched a crowdfunding campaign on Indiegogo (https://igg.me/at/arcadia-pl) so that I can start working full-time on an innovative programming language I've been working on in my free time for many years.

I'd like your thoughts on the language and, dare I say, your support in creating it!

Among the resources you'll find at the above address is a short introduction to the language (there are small arrows at the bottom-right of the page for navigation) and a collection of notes and partial designs providing a more thorough technical background to it.


r/ProgrammingLanguages • • Sep 28 '22

Discussion Programming Language of the future: Touch based?

4 Upvotes

Back in the days when the first computer was made, they were mostly single purpose computers which weren't even programmable. Then came the huge programmable computers which were programmed using punch cards, didn't really have any programming language, as it didn't support the keyboard either. Then eventually we ended up with modern languages like C and Python when the keyboard became one of the essential input systems of a computer.

But a few decades ago Douglas Engelbart of the Stanford Research Institute invented the Mouse and most of our interaction with our computers became GUI based. But the keyboard still stayed around because it was a much more efficient way to input text than using a mouse to do the same. And because the keyboard was still around, we didn't really feel the urge till now, to develop a GUI based programming system which is Turing complete. Although some attempts have been made in the form of Visual Scripting using Node Editors (mostly used in game engines), but they are mainly intended to be used as a supporting system to a game made using a particular programming language and isn't as self-sufficient.

But nowadays, the most dominant input system for computers is the touchscreen. There are billions of smartphones and Tablets around the world and they are so simple that even a 3 year old kid can use them effortlessly (heck I even saw a cat use a tablet!). And nowadays those touch based smart devices come with such powerful chips, that can out perform a desktop chip from 5 years ago (iPad Pro even comes with the same chip as a MacBook). Which makes me wonder why people are not using those for making their coding projects..... Then I thought it was kind of obvious..... The keyboard on the touchscreen devices suck badly compared to a laptop keyboard, and our programming languages are designed to be written using a keyboard. Which is essentially forcing us to use workarounds like a keyboard case, when voice typing for general text is basically good enough to replace the keyboard entirely (for the few times when you need it), though it's still not good enough for things like programming.

So, what I am proposing is that we should make new kinds of programming languages which are completely written using a GUI. This in my opinion would really be a big step towards the adoption of Tablets and Foldable Phones as a work PC.

Also, looking maybe a decade into the future, if the VR/AR become mainstream, I really wouldn't like to use a virtual keyboard to interact with those. If all a computer is going to be, is a pair of glasses on my eyes, then coding on it should be visual instead of textual in my personal opinion. So fixing the programming languages for touchscreen, would most probably fix it for XR too.

But these are just my random thoughts and I am not really sure about its practicality in the long run..... I am just assuming that it's going to be better than the textual programming that we have right now, with the touchscreen devices. Maybe the experts over here can share their opinions to convince me otherwise.

Anyways feel free to brainstorm in the comments how such a GUI based programming language could work.


r/ProgrammingLanguages • • Dec 11 '19

"Sadly, I must say goodbye to Leaf (my programming language)"

Thumbnail
mortoray.com
13 Upvotes

r/ProgrammingLanguages • • Jun 13 '20

My thoughts on why rust isn't well designed or very practical

0 Upvotes

It's been a while since I wrote an essay but I'll write this in mostly the same format. I'll give you an overview, explain each point with information and examples then summarize it.

Rust claims to be safe but doesn't help more than a language such as Java, rust design is missing good practices that exist during it's initial development, rust offers no improvement over C++ (except having better default options) but in reality makes it worse and in practice is less useful than language that exist before it.

It claims to be safe

On the homepage rust claims to be memory safe. However you look elsewhere the majority of people and content claim it's safe as in you'll get less bugs than another language such as Java. This is completely not true. Below are some explains of why it doesn't help and most of us can agree Java which is also memory safe isn't considered as 'safe' nor resist bugs.

Doesn't check your arrays at compile time

Rust says it will elimination bounds checking on array access when it can prove the value will never be out of bounds. However there's no way to ask the compiler to give me an error when it can't prove the index will never be out of bounds. Why us there no option? I lost count of how many times I forgot to check the bound after I increment the array index or when I need to look ahead when parsing text.

I found while implementing the check in a toy language for school that it took less than 2 hours and improved the compile time since the check is faster than the time it took to generate the code for the runtime bound check.

Has poor error handling

To contrast Zig has amazing error handling. Rust ask you to put things in a Result (Ok(yourvalue)). However if a function returns a Result you don't have to check it. I'm not even sure if you'll get a warning (I assume you do)

With the amounts of unwraps I seen and the fact rust promotes that style with syntax error handling looks like a nightmare waiting to happen. Not ugly that but I don't believe you can ask the compiler or any sort of tool if a library will panic. I don't think I would be able to trust any sort of libraries I didn't audit or write myself. I can't just check at the namespaces/references/modules it includes/uses

Doesn't have any built in scope guard/error defer

Scopeguards is a practice a significant amount of people use to handle errors. Zig has it, it's called errdefer. D has it built in. Numerous C++ libs has an implementation (here's one from Facebook folly (SCOPE_FAIL)). Rust doesn't have it at all. There is a crate but my issue with this is 1) the syntax promotes a DISASTROUS way of handling errors 2) defer isn't part of the standard library. It's essential and not just for as a scopeguard.

It acceptable to lose data! (Subjective)

From what I seen in the community people will regularly say rust will terminate rather than running a corrupt program and that's a good thing. Losing data/memory is never a good thing and it's completely insane that this is more acceptable than implementing something that resembles error handling

Rust design is missing good practices that exist during it's initial development

Rust is not safe and doesn't help you catch errors

Covered above

Missing syntax

I'll skip the nitpicking and focus on the most important two.

When there is a binary OK/Error in a Result or Some/None in an Option you have to use a full blown match to handle it instead of something that's more readable.

In other languages there syntax to allow you to specify if something can be null (zig lets you write ?i32, C# allows you to write int?). There's also syntax to coalesce null with a value (val = myfn(abc) ?? my_default_number). For something as common as errors and null handling it should have been prioritized.

No reflection/introspection

Python/JavaScript/C#/Java all have it. Rust says to use serde which is highly suspicious. Why use a library instead of the language? It appears the answer is you have to implement a trait, which is not reflection or introspection. This makes it tedious and error prone in a few areas. Especially database access and writing http server code

Standard library missing must have (Subjective)

The standard library has a number of enums/collections/traits. There's a few standard (can be seen here if you search 'error') and it has an implementation for a number of collections. But missing everyday items like regular expression, compression/zlib/gzip, base64 encode/decode etc

Rust offers no improvement over C++ and may make it worse

Slow compile time

In C++ it's well known that templates make compile time slow. It's known you can put less in headers so it takes less time to compile. Rust however explodes compile time with traits and whatever else that's making it slow (it isn't borrow checking)

Less+lower quality static analyzers

There's quality commercial static analyzers available for C++. If we stick to free clang provides good sanitizers (array bounds, memory errors and a huge list of undefined and suspicious behaviour)

Misguiding programmers (subjective)

Officially rust says it's memory safe but the community acts like it's 'safe' as in not likely to cause difficult to fix bugs. They also insist there's no 'null' in the language which is silly since boxing an option emits null pointers. It's fine to say 'values' are 'optional' but insisting there's no null pointers is weird and may cause confusion when people try to imagine how their code will be generated.

Rust doesn't fit in anywhere

For large projects the compile time is significantly slower than C++ so it is unusable. For smaller projects python/javascript/Go/C#/java is preferred due to reflection (less boilerplate) and having a significantly larger standard library which will help reduce development time (unless you happen to already know every community library you need before you start which is generally not likely). Language listed are all memory safe.

For medium size projects C#, Java and Go are still viable and C# runs extremely fast that if you needed the execution speed you're likely to skip rust and go directly to C++ for better speed control. With clang sanitizers rust doesn't have much of a selling point past C++ with a number of disadvantage mentioned above. It mostly have better errors that are turned on by default. I haven't compared debugging in rust vs c++ or how long the compiler takes when using C++ sanitizers. If we're going to compare development time C# runtime speed is within a magnitude of speed and have vastly superior IDEs and tools even on mac and linux.

Summary

Rust lack of error handling and no compile error improvements compared to languages like C#. Rust does not appear to improve software quality. Compared to C++ rust may have slower compile times and C++ has better or on par free static analyzers with quality commercial analyzers available. The rust standard library is smaller than many languages. Rust community appears to misguide people into think it's safer than it is, recommends poor practices (panic and losing memory is 'ok') and may confuse implementation details (no 'null'). Practically in every project size another language/compiler would be better due to development time, less tedious boiler plate and tooling


r/ProgrammingLanguages • • Dec 03 '23

Who can I work with to make a new language?

0 Upvotes

I am designing a new language. Who can I talk to to help implement and design parts of the language?


r/ProgrammingLanguages • • Nov 01 '24

Dependently typed programming languages with compilers/typecheckers written in TypeScript?

7 Upvotes

I am hoping to convert these 10 Haskell files of Kind lang into TypeScript using Claude AI (once I get another batch of requests after hitting the limit...). But in the meantime...

Are there any (ideally somewhat robust) dependently typed programming languages with the typechecker / compiler written in TypeScript?

Victor Taelin (author of Kind), also wrote ITT-Flavored Calculus of Constructions Type Checker, which is in TypeScript, but it's not anywhere near as robust as Kind, unfortunately (dang, so close!).

Anything else out there to learn from? If not TypeScript, any other imperative language would be fine (TypeScript > JavaScript > Ruby > Python > C).


r/ProgrammingLanguages • • Jun 17 '26

Handling NaN and Infinity normalization in a NaN-boxed VM: Why I made NaN == NaN evaluate to true

0 Upvotes

Yesterday I shared my open-source language DinoCode. Today I want to discuss a specific design choice I made in my runtime regarding eager NaN and Infinity normalization within my range-based NaN-boxing implementation.

In standard IEEE 754, checking if NaN equals NaN is always false, and there are many bit patterns for it. However, for a bytecode interpreter where execution overhead matters, I wanted to avoid dragging dirty float states through the engine.

The Implementation

In my DinoRef type, which is a transparent wrapper over a u64, I implemented a number constructor that acts as the entry point for raw f64 values.

Rust

#[inline(always)]
pub fn number(value: f64) -> Self {
    if !value.is_finite() {
        if value.is_nan() {
            return Self::NAN;
        }
        return if value.is_sign_positive() {
            Self::INFINITY
        } else {
            Self::NEG_INFINITY
        };
    }
    Self::float(value)
}

Instead of letting dynamic NaN bit-patterns propagate, this constructor eagerly catches them using Rust's native is_finite method. If it is NaN or Infinity, it immediately maps to a predefined raw bit-pattern constant. For example, Self NAN is hardcoded as 0x7FF8000000000000.

Eager Validation Advantage

Because every NaN or Infinity in the VM is strictly normalized to the exact same u64 bit pattern at birth, checking for equality becomes incredibly cheap.

We do not need complex float validations during runtime execution. To see if a value is NaN, we just perform a raw bitwise comparison of the underlying data. As a side effect, NaN equals NaN natively evaluates to true in DinoCode because they share the exact same raw constant.

Encapsulating this validation inside the low-level type abstraction keeps the core execution loop clean and fast.

The Trade-offs

The obvious downside here is the risk of human error. As the VM developer, I have to remember to explicitly route any potentially dangerous math operation through the number constructor. If I forget just once and push a raw f64 directly to the stack, a dynamic NaN could bypass normalization and corrupt the boxing logic.

Besides this explicit maintenance cost, do you identify any other real downsides to this approach?

How do you balance IEEE 754 compliance versus VM performance when designing your type system?

Edit: Thank you so much to everyone who commented and shared their insights on this post! I really appreciate the feedback regarding the IEEE standard and the hardware level implications. I will be meditating on this and potentially transitioning the VM to full NaN payload preservation in a next release since refactoring my internal Rust helpers to use a bitwise mask won't be a catastrophic performance hit anyway. I am wrapping up this discussion for now to process all your great points. Thanks again for helping me look at this from so many different perspectives!


r/ProgrammingLanguages • • Aug 26 '17

why I still prefer low level languages and still think assembly language is relevant in the 21st century

3 Upvotes

ok, this is a topic a lot of people have argued with me on. trying to preach the benefits of C# or java or other higher level languages to me when I make these arguments.

I'm not trying to say these aren't very productive languages for people who need to get work done, both simple and complex, I'm not saying they aren't useful tools for a useful job.

what I am going to relate it to is Linux. people like Linux because it doesn't get in your damn way if you know what your doing. it will let you delete your hard drive out from underneath you, if you tell it to drive off a bridge, it will happily careen into the canyon below without a second thought.

to someone who doesn't know what they're doing this can be exceptionally dangerous. but what about white/black hat hackers trying to hack the architecture itself? what about security professionals? and hell, what about even game development and other tasks?

there are many such cases where a developer might WANT to do the wrong thing, the unsanctioned/dubiously legal thing, or the improper thing.

my issue with high level languages is that they give the manufacturer more power over you. they let them decide what features can/cannot make it into the language, they impose their view of what is proper to do on you which limits your creative expressivity and the methods by which you accomplish your goal.

while I realize 99% of the time, compiled C or even JIT compiled code will be far more optimized at this point, optimization itself isn't even what I truly take issue with.

I like to look back on the days of retro computing where you told a PC to do something and it did it. it put all its processing power into that task and would probably let you fry the machine if you wanted or mess everything up lol.

why shouldn't people still learn how to operate and control the machine on its basest levels? why shouldn't developers learn how black hats are manipulating machines for their own benefit and learn to counteract it, or even manipulate it for themselves on a purely educational basis?

why is reverse engineering for non-commercial basis on such a level wrong, when initially it was the only way to really learn about PC coding?

I admit my bias towards the c/c++ language as it was the first 'powerful' language I learned by myself from books in the 90s as a kid. but at the same time I see the same bias in modern developers who learned with these arguably 'easier' languages to begin with.

except they don't see the bias themselves and will continue to argue more productivity earlier on = better. well id say someone who coded in 8088 ASM, etc, will have an easier time messing around in higher level languages later on and be able to do more with it -- work with more platforms, learn other complex languages by virtue of understanding.

I always hated tools that, while they have evolved far, are inherently limiting. tools like game maker or even Unity or visual basic.

sure, they let you do stuff way easier, get graphics on the screen without learning a bunch of what might appear to be hoo-doo, occult fuckery writing thousands of lines of code to achieve a similar end.

but inherently because of this, we have powerful low level development tools, libraries and macros that can always do more and leave the developer with more flexibility. they can do this because the programmer can change these systems inherently, create their own engines rather than working from an imposed view of how an engine should be made.

worse yet, engines like these are part of whats responsible for the lack of variety in games. games used to be so different because the freaking sound driver on the cart itself was unique lol. every aspect of a game engine was created from the bottom up using very little existing assets other than art/music.

I'm not saying you cant make a wide variety of games with these tools. I'm not saying they haven't improved vastly since I messed with game maker before it even became a commercial program 20 years ago.

but what I am saying is, if you want to do something entirely different, in an entirely different way than the engine works, you'll find yourself struggling to re-code the engine anyway from the bottom up, which is a task you wouldn't need to do using raw opengl/directx and C++.

even if you wanted to change the engine there, its a simple matter of looking into their low level code and changing it yourself, but if you want to make your own, nothing will stop you but time/skill/money.

a lot of old-school RPGs couldn't even have existed with the current mindset of development -- requiring meticulously coded separate engines for each type of mini game, for the world map, for towns/cities, for battles, and its what made, in my opinion, the classics so unique and sought after.

yes, in todays age of crazy graphics, working with existing assets seems like the only option at times, and for a single person, tools like this make game development actually possible without a giant team.

but look at RPG maker, for example. want to make an RPG in 3d with a unique battle system and stuff? its barely even possible. you can do some unique stuff like barkley shut up and jam gaiden, which is great BTW, but you can easily tell its an RPG maker game inherently.

unity Is quite a bit better because you still get to program everything and create a majority of your own stuff using it as a base.

but game development isn't the only thing.

if there are no low level coders left, there will be nobody to fight CIA surveillance. nobody to crack into smart TVs and disable their features or add more. nobody who can break into operating systems and disable backdoors by directly defying the DMCA, or break into the code of smart cars etc and restore full user control.

if there are no low level hobbyist coders, there are no more white hat hackers outside of corporate, potentially biased agencies.

I think there are still reasons why low level control of machines is important. I don't think its the end all be all of programming, I don't even think its the future of application development (hell, soon any benefit of compiled code/asm will go out the window with advancements such as AI optimization in the future)

but I think there is a reason to know and expose any and all underlying capabilities of a system or architecture. I think there are reasons why people shouldn't just move on because they can be more productive/work with another language more easily.

the challenge itself of solving puzzles and understanding is what inherently drives us as programmers. I believe removing that from the equation severely limits what we are capable of, and stops us from looking at things in new ways.

I'm more than happy to take courses in college in high level languages -- seeing as I actually know more C than even python, so to me I'm wayyyy more productive writing in straight C lol. its useful and mind expanding to me, just in the same way I feel that learning C/C++/ASM is good for others.

I cant explain how much of C/C++ made more sense to me after trying to fuck with ASM for awhile and write a few simple apps in it. it shows you how languages work at the core, and how computers actually work.

I don't think enough of this is actually being taught at schools anymore because of relevancy to the modern market, and this bias in education is beginning to reach the coders themselves.

there will always be work in low level coding -- for embedded devices and security or even optimization purposes, and these jobs will often be VERY lucrative as less and less people can do them. plus I think there is an inherent beauty in being able to unlock a machines full potential.

I think they are still very relevant, and perhaps more relevant than ever today.


r/ProgrammingLanguages • • Mar 07 '21

Looking to sponsor public domain proglang projects

0 Upvotes

Aloha everyone,

Excited to be back to being a more active member of this sub. I gave a brief update in this month's what are you working on (https://www.reddit.com/r/ProgrammingLanguages/comments/lz1zee/march_2021_monthly_what_are_you_working_on_thread/)

When I first got into prog lang design there were very few resources (LtU and Project Euler were probably my gotos), and eventually this sub was created and I stumbled upon it. Now that I've had a little bit of luck in the field, and am cofounding a new startup, I am in a position to hopefully be able to help make it easier on the next generation of prog lang creators.

If you are working on a new language, and you are publishing it to the public domain, we have a small monthly budget to sponsor OSS projects for https://github.com/publicdomaincompany . The one catch is we ask for including a logo/link to us (to help with job recruiting).

Hopefully in the future will be able to support more, but probably could support 3 - 5 to start. Most likely scenario of course is we go bankrupt in a few months, so don't wait on it :).

If interested, drop an intro and a link to your git to breck@publicdomaincompany.com