DEV Community

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

Ben Halpern on April 18, 2018

Collapse
 
pbouillon profile image
Pierre Bouillon • Edited

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.

Collapse
 
oivoodoo profile image
Alexandr K

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

Collapse
 
rhymes profile image
rhymes

Fortunately it's gone in Python 3:

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

:D

Collapse
 
pbouillon profile image
Pierre Bouillon • Edited

It's no longer an integer :)

Thread Thread
 
val_baca profile image
Valentin Baca

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
Thread Thread
 
pbouillon profile image
Pierre Bouillon • Edited

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.
Collapse
 
tamas profile image
Tamás Szelei

That readme is excellent, thanks for posting it!

Collapse
 
cgcnu profile image
sreenivas

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

Collapse
 
ben profile image
Ben Halpern • Edited

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.

Collapse
 
dance2die profile image
Sung M. Kim • Edited

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)...
Collapse
 
chrisvasqm profile image
Christian Vasquez • Edited

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().

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

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
Collapse
 
dwd profile image
Dave Cridland

Lots of languages support that, including most obviously Javascript.

Collapse
 
alainvanhout profile image
Alain Van Hout

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

Collapse
 
dance2die profile image
Sung M. Kim • Edited

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
Collapse
 
vinaypai profile image
Vinay Pai

This is pretty neat

Collapse
 
dance2die profile image
Sung M. Kim

Thanks Vinay.

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

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.

Collapse
 
dubyabrian profile image
W. Brian Gourlie

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?

Collapse
 
mortoray profile image
edA‑qa mort‑ora‑y

π 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.

Collapse
 
chrisvasqm profile image
Christian Vasquez • Edited

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
}
Collapse
 
dance2die profile image
Sung M. Kim • Edited

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
Collapse
 
dwd profile image
Dave Cridland

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.

Collapse
 
dance2die profile image
Sung M. Kim

Thanks Dave.
There is no end to learning.
I feel humbled :)

Collapse
 
rhymes profile image
rhymes

Same in Python

>>> [a, b] = [1, 999]
>>> a, b
(1, 999)
>>> [b, a] = [a, b]
>>> a, b
(999, 1)
Collapse
 
dance2die profile image
Sung M. Kim

Python has been on my mind lately. That's yet another good reason ;p

Collapse
 
dwd profile image
Dave Cridland

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();
}
Collapse
 
scottishross profile image
Ross Henderson • Edited

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;
 
dwd profile image
Dave Cridland

Right - something like this is fine:


class Foo {
  method1() {
    console.log("Method one")
  }
}

Foo.prototype.method2 = function(){ console.log("Method too") }

Thanks to the batshit insane way that this works, it's a full-blown method.

This capability isn't unusual. In Python, you can also add methods to instances, but you need to ensure you handle self:

class Foo:
  def __init__(self):
    # Some code

f = Foo()

dir(f) ## Returns ['__doc__', '__init__', '__module__']

Foo.method = lambda self, x: x

dir(f) ## Now includes our new method

f.method(22) ## Returns 22.

Languages such as C++ and Java, on the other hand, have immutable types (and in the former, types aren't themselves even a type).

Collapse
 
itsjzt profile image
Saurabh Sharma
1 == '1' // true
1 === '1' //false 

JavaScript

Collapse
 
khophi profile image
KhoPhi • Edited

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

Collapse
 
kspeakman profile image
Kasey Speakman • Edited

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.

Collapse
 
nickforall profile image
Nick Vernij

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
Collapse
 
sam_ferree profile image
Sam Ferree

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...

Collapse
 
dwd profile image
Dave Cridland

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).

Collapse
 
stefandorresteijn profile image
Stefan Dorresteijn • Edited

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!")
Collapse
 
vekzdran profile image
Vedran Mandić

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/

Collapse
 
itsasine profile image
ItsASine (Kayla)

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

Basically just having fun with on the fly type conversion

Collapse
 
alexandrugrusu profile image
Alex George • Edited

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

 
dwd profile image
Dave Cridland

Yeah - sorry, meant to demonstrate that you can attach a function via prototype to a class defined with class syntax.

Collapse
 
demuirgos profile image
Ayman Bouchareb

F# typeproviders are just LOVE