Write a function that shows off something unique or interesting about the language you're using

Did you find this post useful? Show some love!

Unique and interesting, but awful

Python 2.X:

>>> True
True
>>> True = False
>>> True
False

Python is full of very tricky things ! I had a lot of fun reading this README which explains them.

never know it. it looks like js nightmare. :)

Fortunately it's gone in Python 3:

>>> True
True
>>> True = False
  File "<stdin>", line 1
SyntaxError: can't assign to keyword

:D

It still is. bool is a subclass of int:

$ python3
Python 3.6.5 (default, Mar 30 2018, 06:42:10)
[GCC 4.2.1 Compatible Apple LLVM 9.0.0 (clang-900.0.39.2)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> isinstance(True, int)
True
>>> isinstance(False, int)
True

Shameful mistake, thanks for clarifying ! I meant that they had their own type now, indeed from integer.

Full explanation

Initially, Python used to have no bool type 
(people used 0 for false and non-zero value like 1 for true). 
Then they added True, False, and a bool type, but, for backward
compatibility, they couldn't make True and False constants- they 
just were built-in variables.

That readme is excellent, thanks for posting it!

Ah!!! Looks like Python is a distant relative of Javascript!!

In Ruby we can monkeypatch to easily add functionality to any class.

For example:


class String

  def yell!
    self.upcase + "!!!"
  end

end

I'm extending the string class so that "hello".yell! outputs "HELLO!!!"

And now all strings in the program have access to the yell! method. ❀️

I'll add that this is sort of bonkers and an easy way to add some really hard-to-debug code to an app. Use with great fear and caution.

That's amazing that Ruby and other languages can extend built-in classes as well.

Anyways, to show off C#, here you go.

C# can extend any classes using extension method syntax.

using System;

namespace extensionmethod
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!".Yell());
        }
    }

    public static class StringExtensions
    {
        public static string Yell(this string message)
        {
            return $"{message.ToUpper()}!!!";
        }
    }
}

Outputs

c:\misc\Sources\throwaway\extensionmethod>
$ dotnet run
HELLO WORLD!!!!

Note that you should mark the parameter with this

Yell(this string message)...

Here's how this would look in Kotlin:

fun String.yell() = this.toUpperCase()

Another interesting use is to create an Extension Property so you can print any type to the console, like this:

// Define the extension property
val Any.sout
    get() = println(this)

Which can be used like:

fun main(args: Array<String>) {
    "hi".sout // prints hi
    123.sout  // prints 123
    true.sout // prints true
}

Since this is also available on any other class, any object you create will also have this property and it will call their toString().

In F# it is also easy to add functionality to existing classes.

type String with

    member me.yell () =
        me.ToUpper() + "!!!"

You can also add functions to existing static classes (modules) too.

module Array =
    let shuffle arr =
        ...

[| for i in 0 .. 23 do yield i * i |]
    |> Array.filter isOdd   // filter is built-in
    |> Array.shuffle        // i added

Lots of languages support that, including most obviously Javascript.

Interesting. Is that possible via class definitions (class syntax I mean) or only via the prototype syntax?

A PowerShell script to get 5 most CPU intensive processes.

PowerShell passes .NET CLI object(s) into the next pipeline (<-- this is most unique feature of all shells) so there is need to parse text as you do in other shells (using sed or awk).

PS C:\misc\sources> gps | sort -desc cpu | select -first 5 id, cpu, processname

   Id         CPU ProcessName
   --         --- -----------
 9352 7230.578125 firefox
13124 6531.015625 firefox
10460      6419.5 firefox
 2296  6017.03125 firefox
 9172 4406.453125 firefox
Ben Halpern DEV.TO FOUNDER

Hey there, we see you aren't signed in. (Yes you, the reader. This is a fake comment.)

Please consider creating an account on dev.to. It literally takes a few seconds and we'd appreciate the support so much. ❀️

Plus, no fake comments when you're signed in. πŸ™ƒ

Leaf stores literals (constants) as rational numbers and is type safe.

good is assigned the value 1 -- there is no precision loss on the division.

err produces a compiler error since 1/3*2 is not an integer.

Woah. How do rational numbers interact with irrational numbers in this case? Are they approximated prior to any sort of arithmetic or are they considered incompatible types?

Ο€ and 1/2 were my two motivating reasons for making this feature.

For irrationals, and other fractions, the system will switch to a high-precision floating point mode instead of a rational -- I honestly don't remember what the trigger criteria actually is, I think size of the rational.

What this allows however is that Ο€ is a single constant you can define to 100 decimal places. This is high enough precision that several constant operations, basic math, can work on this value without losing precision when converting to the actual system type. It doesn't matter if you convert to a 32/64/128-bit float, it'll have the full precision for that type. No need for constants per type, or stuff like M_PI2.

Note this precision only applies to constants. Runtime variables are limited by the standard system types. Sometime later I'll add these numbers are runtime, but they're fairly special purpose at that point. The literal folding now is enough to cover the current intended use-cases.

Kotlin has this concept of infix functions, which means they are an extension function that has only 1 parameter and allows us to use them without the dot (.) operator and no parentheses (but you can also do it the normal way, if you want to).

Declare the infix function

infix fun Int.times(base: Int) = this * base

Example

fun main(args: Array<String>) {
    println(10 times 5)  // prints 50
    println(10.times(5)) // also prints 50
}

Javascript... Yes, Javascript is a barrel of pure quirk. Just pick variable scope. As if it wasn't bad enough that hoisting exists, the bizarre way scopes work allows you to write some truly awe-inspiring hackery, like this Fibonacci function:


function fib(n) {
  if (n) {
    a = 1;
    b = 0;
    c = n + 1;
  }
  if (c === 1) {
    return a + b;
  }
  c = c - 1;
  let d = a + b;
  b = a;
  a = d;
  return fib();
}

JavaScript lets you swap variables without a temporary variable.

$ node
> let a = 1, b = 999
undefined
> [b, a] = [a, b]
[ 1, 999 ]
> a
999
> b
1

So does C:

int a = 1, b = 999;
a ^= b;
b ^= a;
a ^= b;

OK, so this is specific to numeric values, actually, but it comes in handy in cryptographic code for constant time conditional swaps and things.

Same in Python

>>> [a, b] = [1, 999]
>>> a, b
(1, 999)
>>> [b, a] = [a, b]
>>> a, b
(999, 1)

It isn't that difficult to generate the Fibonacci Spiral through Oracle SQL :)

with FIBONACCI (i, FIBO, PREV) as 
(
   select 
      1 i,
      0 FIBO,
      cast( null as number ) PREV 
   from 
      DUAL
   union all
   select 
      f1.i + 1  i,
      f1.FIBO + nvl(f1.PREV,1) FIBO,
      f1.FIBO PREV
   from 
      FIBONACCI f1
   where 
      f1.i < 20
)

select 
   FIBO
from 
   FIBONACCI
order by 
   i;

An interesting one I can think of in Python.

Reversing a string

'hello world'[::-1]

How's written in other common languages too can be seen side by side

        /// <summary>
        /// The variable value.
        /// </summary>
        public object Value
        {
            get
            {
                if (parentModel != null)
                {
                    var mi = parentModel.Type.GetMember(Name);

                    if (mi.Length > 0)
                    {
                        if (mi[0] is FieldInfo)
                        {
                            value = ((FieldInfo)mi[0]).GetValue(parentObject);
                            return value;
                        }
                        else if (mi[0] is PropertyInfo)
                        {
                            if (parentModel.Type is System.Collections.IEnumerable)
                            {
                                value = ((PropertyInfo)mi[0]).GetValue(parentObject, new object[] { index });
                                return value;
                            }
                            else
                            {
                                value = ((PropertyInfo)mi[0]).GetValue(parentObject);
                                if (parentModel.PropertyChanged != null)
                                    parentModel.PropertyChanged(this, new PropertyChangedEventArgs("Members"));
                                return value;
                            }
                        }
                        else
                            return value;
                    }
                    else
                        return value;
                }
                else
                    return value;
            }
            set
            {
                if (parentModel != null)
                {
                    var mi = parentModel.Type.GetMember(Name);

                    try
                    {
                        if (mi != null && mi.Length > 0)
                        {
                            bool didSet = false;
                            if (value is string)
                            {
                                TypeConverter tc = TypeDescriptor.GetConverter(Type);
                                this.value = tc.ConvertFromString((string)value);
                            }

                            if (mi[0] is FieldInfo)
                            {
                                var fInfo = mi[0] as FieldInfo;
                                var val = fInfo.GetValue(parentObject);

                                if (val != this.value)
                                {
                                    this.value = val;
                                    fInfo.SetValue(parentObject, this.value);
                                    didSet = true;
                                }
                            }
                            else if (mi[0] is PropertyInfo)
                            {
                                var pInfo = mi[0] as PropertyInfo;
                                if (parentModel.Type is System.Collections.IEnumerable)
                                {
                                    var val = pInfo.GetValue(parentObject, new object[] { index });

                                    if (val != this.value)
                                    {
                                        this.value = val;
                                        pInfo.SetValue(parentObject, this.value, new object[] { index });
                                        didSet = true;
                                    }
                                }
                                else
                                {
                                    var val = pInfo.GetValue(parentObject);

                                    if (val != this.value)
                                    {
                                        this.value = val;
                                        pInfo.SetValue(parentObject, this.value);
                                        didSet = true;
                                    }
                                }
                            }
                            else
                            {
                                this.value = value;
                                didSet = true;
                            }

                            if (PropertyChanged != null && didSet)
                                PropertyChanged(this, new PropertyChangedEventArgs("Value"));
                        }
                    }
                    catch
                    {
                        throw new MemberAccessException("The member cannot be set in this way.");
                    }
                }
            }
        }
        private object value;

What can I say, reflection is handy for a debugger.

Another contender, though for a different language:

mt.__index = function(self,key)
    local k = self.data[key]
    local metatable = getmetatable(k)
    if key == 'data' or not k then
        return rawget(self, key)
    elseif type(k) ~= 'function' and (metatable == nil or metatable.__call == nil) then
        return k
    else
        return function(...)
            if self == ... then
                return k(self.data, select(2,...))
            else
                return k(...)
            end
        end
    end
end

One does not underestimate the power of metatables in Lua, particularly when having to differentiate between userdata fields and Lua table fields.

1 == '1' // true
1 === '1' //false 

JavaScript

And another one. C++ can do some pretty impressive things at build time. In the case of Fibonacci, we can declare it as a template function, and let it get calculated during compilation:

#include <iostream>

template<int i> int fib() {
        return fib<i-1>() + fib<i-2>();
}
template<> int fib<0>() {
        return 0;
}
template<> int fib<1>() {
        return 1;
}

int main(int argc, const char ** argv) {
        std::cout << fib<20>() << std::endl;
}

In the above, there's no recursion at runtime - it's all in the compiler.

Or, in C++ 11 and beyond, we get constexpr, which will give us the same thing, but allow the function to be called normally at runtime as well:

#include <iostream>

constexpr int fib(int i) {
        if (i == 0) return 0;
        if (i == 1) return 1;
        return fib(i-1) + fib(i-2);
}

int main(int argc, const char ** argv) {
        std::cout << fib(20) << std::endl;
}

This (I think) is still calculating the result at compile time - but if we used a variable instead of 20, it'd calculate it at compile time. As far as whether the code would recurse twice at each level, though, that's up to how clever the compiler is feeling - we've told it (with constexpr that the results are always the same).

C# and null safe navigation

// baz is null
// doesn't throw null refernce exception
return foo?.bar?.baz?.bim?.bo?.ban; //returns null

Saves sooo many null checks...

Pattern matching in elixir can be pretty cool

defmodule Fib do 
  def fib(0) do 0 end
  def fib(1) do 1 end
  def fib(n) do fib(n-1) + fib(n-2) end
end

Not a function but a fun little bit of code. It's not all that interesting but it shows how easy it is to write code without defining variables in Elixir, which cleans up your code a lot!

IO.puts "na "
|> String.upcase
|> String.duplicate(8)
|> Kernel.<>("Batman!")

There are lots of things I like about F#. Probably one that is unique though is its computation expressions. Here is a list example.

// a list normally is defined like this: [ 1; 2; 3 ]
let validate course =
    [
        // but the compiler knows this is a CE
        // because we put logic in it

        if isBlankish course.Name then
            yield "Course Name blank"

        match course.Exam with
            | None -> () // do nothing
            | Some exam ->
                yield! Exam.validate exam
                // the ! is for other lists, flattens
    ]

...

// errors : string list
let errors = validate course

This provides a list of errors. And it is composable with other validations. It could be called in the same way that this function calls Exam.validate.

eval(atob('QXJyYXkoMTYpLmpvaW4oImEiLTEpICsgIiBCYXRtYW4hIjs')) safe and fun to run and related to Batman! Jokes aside, to summarize, this guy pushes JavaScript to the limits: aem1k.com/

function somethingunique(){
$hereitis="I can always google and stack overflow got my back";
echo $hereitis; 
}
somethingunique()

I made a codepen of a 4chan greentext about Javascript logic

Basically just having fun with on the fly type conversion

<?php
function helloworld(){
$somethingunique="I can always google";
echo $somethingunique;
}
helloworld()
?>

In bash:

for i in {1..12}; do for j in $(seq 1 $i); do echo -ne $i×$j=$((i*j))\t;done; echo;done

imgur.com/Z7jWFhI

Classic DEV Post from Apr 29

What are the latest trends in front-end JavaScript?

What are the newest popular ideas and/or projects? What's trending up and what'...

READ POST
Follow @ben to see more of their posts in your feed.
Ben Halpern
A Canadian living in New York, having a lot of fun cultivating this community! Creator and webmaster of dev.to.
More from @ben
Write a function that outputs a pleasant text color hex given a background color hex
#challenge
Trending on dev.to
When to give a star to an open sourceΒ library?
#opensource #developers #community #discuss
Spot the malware
#security #challenge #punycode
How much should you refactor names when domain terminology changes?
#discuss #refactoring
The Shell Introduction I Wish I Had
#shell #productivity #beginners #bash
What are your programming hype songs?
#discuss #music #productivity
Note taking as a developer
#discuss #notes
How do you keep track of what you're reading?
#discuss
I have $1,000 for use for technical stuff provided by my company, what should I get?
#discuss