loading...

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

ben profile image Ben Halpern ・1 min read

Discussion

pic
Editor guide
Collapse
pbouillon profile image
Pierre Bouillon

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

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

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 Author

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

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

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

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

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
dance2die profile image
Sung M. Kim

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
chrisvasqm profile image
Christian Vasquez

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
scottishross profile image
Ross Henderson

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;
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();
}
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
jesuszilla_tm profile image
Jesuszilla イエスジラ
        /// <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.

Collapse
jesuszilla_tm profile image
Jesuszilla イエスジラ

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.

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

JavaScript

Collapse
khophi profile image
KhoPhi

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
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
kspeakman profile image
Kasey Speakman

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
stefandorresteijn profile image
Stefan Dorresteijn

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
ronniengoda profile image
Ronald Ngoda
function somethingunique(){
$hereitis="I can always google and stack overflow got my back";
echo $hereitis; 
}
somethingunique()
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

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
alexandrugrusu profile image
Alex George

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

Collapse
ronniengoda profile image
Ronald Ngoda

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