Skip to content

Instantly share code, notes, and snippets.

@amirrajan
Created February 8, 2018 02:31
Show Gist options
  • Save amirrajan/b023426d2b8366fb4fe74c7e17618986 to your computer and use it in GitHub Desktop.
Save amirrajan/b023426d2b8366fb4fe74c7e17618986 to your computer and use it in GitHub Desktop.
Language Tour

Language Tour

Ruby

Story

v=0000;eval$s=%q~d=%!^Lcf<LK8,                  _@7gj*LJ=c5nM)Tp1g0%Xv.,S[<>YoP
4ZojjV)O>qIH1/n[|2yE[>:ieC       "%.#%  :::##"       97N-A&Kj_K_><wS5rtWk@*a+Y5
yH?b[F^e7C/56j|pmRe+:)B     "##%      ::##########"     O98(Zh)'Iof*nm.,$C5Nyt=
PPu01Avw^<IiQ=5$'D-y?    "##:         ###############"    g6`YT+qLw9k^ch|K'),tc
6ygIL8xI#LNz3v}T=4W    "#            #.   .####:#######"    lL27FZ0ij)7TQCI)P7u
}RT5-iJbbG5P-DHB<.   "              ##### # :############"   R,YvZ_rnv6ky-G+4U'
$*are@b4U351Q-ug5   "              #######################"   00x8RR%`Om7VDp4M5
PFixrPvl&<p[]1IJ   "              ############:####  %#####"   EGgDt8Lm#;bc4zS^
y]0`_PstfUxOC(q   "              .#############:##%   .##  ."   /,}.YOIFj(k&q_V
zcaAi?]^lCVYp!;  " %%            .################.     #.   "  ;s="v=%04o;ev"%
(;v=(v-($*+[45,  ":####:          :##############%       :   "  ])[n=0].to_i;)%
360)+"al$s=%q#{  "%######.              #########            "  ;;"%c"%126+$s<<
126}";d.gsub!(/  "##########.           #######%             "  |\s|".*"/,"");;
require"zlib"||  "###########           :######.             "  ;d=d.unpack"C*"
d.map{|c|n=(n||  ":#########:           .######: .           "  )*90+(c-2)%91};
e=["%x"%n].pack   " :#######%           :###### #:          "   &&"H*";e=Zlib::
Inflate.inflate(   "  ######%           .####% ::          "   &&e).unpack("b*"
)[0];22.times{|y|   "  ####%             %###             "   ;w=(Math.sqrt(1-(
(y*2.0-21)/22)**(;   " .###:             .#%             "   ;2))*23).floor;(w*
2-1).times{|x|u=(e+    " %##                           "    )[y*z=360,z]*2;u=u[
90*x/w+v+90,90/w];s[(    " #.                        "    ;y*80)+120-w+x]=(""<<
32<<".:%#")[4*u.count((     " .                   "     ;"0"))/u.size]}};;puts\
s+";_ The Qlobe#{" "*18+ (       "#  :#######"       ;"Copyright(C).Yusuke End\
oh, 2010")}";exit~;_ The Qlobe                  Copyright(C).Yusuke Endoh, 2010

Primitives

person = { first_name: 'amir', last_name: 'rajan' }

person[:first_name]

var person = new Dictionary<string, object>() { { "first_name", "amir" } }
"first_name"

Nil Punning, Falsey, and Truthy

some_method() && some_other_method()
some_method() || some_other_method()

person[:first_name] >> nil

people[15] >> nil

var person = people.FirstOrDefault(p => p.);

var lastName = "";
if(people[15] != null)
people[15]?.LastName
end

find_person(199238) && last_name = find_person(199238).last_name

`new`

class Logger
  def debug message
    puts "#{DateTime.now} DEBUG: #{message}"
  end
end

logger = Logger.new
class DatabaseLogger < Logger
  def debug message
    # code to log to the database
  end
end

class ConsoleLogger < Logger
  def initialize
    super

  end
  def debug message
    # code to log to the database
  end
end

class Logger
  class << self
    :alias :new :__new__

    def self.new
      return DatabaseLogger.__new__ if ENV['Logger'] == :database

      ConsoleLogger.__new__
    end
  end

  def format_message

  end
end

Objective C

Story

I had to use it.

Message Passing

Person* person;

id person;

[person sayHelloTo: @"Other Person"];

person.sayHello "other prerson"

person.send(:sayHello, "other person");

person.sayHello()

The important point is that the name and structure of these messages is not necessarily fixed beforehand in the source code and can itself be additional information. This is an important part of what Alan Kay originally envisioned as “object oriented programming”.

Protocols

@protocol XYZPieChartViewDataSource
- (NSUInteger)numberOfSegments;
- (CGFloat)sizeOfSegmentAtIndex:(NSUInteger)segmentIndex;
@optional
- (NSString *)titleForSegmentAtIndex:(NSUInteger)segmentIndex;
@end

Macros

/**
 * Like RCT_EXTERN_REMAP_METHOD, but allows setting a custom JavaScript name
 * and also whether this method is synchronous.
 */
#define _RCT_EXTERN_REMAP_METHOD(js_name,
method,
is_blocking_synchronous_method) \
  + (const RCTMethodInfo *)RCT_CONCAT(__rct_export__, RCT_CONCAT(js_name, RCT_CONCAT(__LINE__, __COUNTER__))) { \
    static RCTMethodInfo config = {#js_name, #method,
is_blocking_synchronous_method}; \
    return &config; \
  }

Scala

Story

Rails is single threaded. Spray.io is cool.

Implicits

scala> def implicitPrinter(implicit str:String) = println(str)
implicitPrinter: (implicit str: String)Unit

scala> implicitPrinter
<console>:9: error: could not find implicit value for parameter str: String
              implicitPrinter

scala> implicit val abra = "abrakadabra"
abra: java.lang.String = abrakadabra

scala> implicitPrinter
abrakadabra

For Comprehensions and Futures

val res = for {
   r1 <- future1()
   r2 <- future2()
   r25 = future25()
   r3 <- future3(r25)
   r4 <- future4()
} yield (r1 + r2 + r3)

Scalaz, Lenses

val firstEventL = Lens.lensu[EventContainer, Event](
   (container, value) => container.copy(events = Seq(value) ++ container.events.tail), _.events.head)

val profileL = Lens.lensu[Event, Profile](
  (event, value) => event.copy(profile = value), _.profile)

val reservationL = Lens.lensu[Profile, Reservation](
  (profile, value) => profile.copy(reservation = value), _.reservation)

val settingAllProperties =
  firstEventL =>=
  { _.copy(eventTitle = "New Title") } andThen
  firstEventL >=> profileL =>=
  { _.copy(profileName = "New Profile Name") } andThen
  firstEventL >=> profileL >=> reservationL =>=
  {
    _.copy(
      reservationComments = "New Comments",
      spaceReservations = Seq(
        SpaceReservation(1111),
        SpaceReservation(2222)))
  } apply ec


val settingJustOneProperty =
  firstEventL >=> profileL >=> reservationL =>=
  { _.copy(reservationComments = "New Comments") } apply ec

Clojure (Lisps)

Story

Simple Made Easy: https://www.infoq.com/presentations/Simple-Made-Easy Light Table: https://www.youtube.com/watch?v=H58-n7uldoU Most Beautiful Progeram Ever Written: https://www.youtube.com/watch?v=OyfBQmvr2Hc

Functions

class Animal {
  constructor(name) { }
  move(aDistanceOf) { }
}

class Snake extends Animal {
  move(aDistanceOf) { }
}

class Horse extends Animal {
  move(aDistanceOf) { }
}

let sam = new Snake("Sammy the Python");
let tom = new Horse("Tommy the Palomino");

sam.move();
tom.move();
function move(aDistanceOf){
  var it = this.name || "It";
  return it + " moved " + aDistanceOf + " meters.";
}

var snake = { name: "Sammy" };
var horse = { name: "Tommy" };

move.call(snake, 5);
move.call(horse, 45);

Explanation

Functional JavaScript: http://leongersing.tumblr.com/post/11561298378/my-perception-of-coffeescript

That’s it. Now, I know what you’re thinking, “Leon, please, [the class oriented example] is contrived and doesn’t represent real world domains.” You’re right and so is [my function oriented example] as a result. “But you also didn’t create real domain models.” Also right, because I didn’t have do, nor would I ever want to. Therein lies my point.

Sometimes a struct is a struct and not an class. The difference that I’m desperately trying to convey in this overly simple context is that by leveraging FP over OO (he really means class oriented, not OO) one can provide not only a more dependable abstraction but when combined with JavaScript’s inherent flexibility as a language, we can achieve true referential transparency and polymorphism.

and also:

FP encourages building small functions that do not mutate state and can be bound together as needed to perform a task whereas the OO [class oriented] philosophy is to encapsulate and achieve polymorphism through interface or contract. The more dynamic your context the more OO’s [class oriented] encapsulation paradigm, as seen in the inheritance model, leaks..

Parenthesis, Blocks, Tokens

function render(person, favoriteColor) {
  return (
    <div
      data-first-name={person.firstName}
      data-last-name={person.lastName}
      style={{ backgroundColor: favoriteColor }}>
      Hello World
    </div>
  );
}
(defn render (person favorite-color)
  (:div
   (:data-first-name (:first-name person)
    :data-last-name (:last-name person))
    :style (:background-color favorite-color)
    "Hello World"))
<div class="section">
 <p>
   You walk into the shop. A midget stands behind the counter on a
   stool. He occasionally props himself up with locked arms and dangles
   his feet in the air.
 <div>
 </p>
   <a style="margin: 0; padding: 0"
      href="javascript:;"
      onClick="buyItem()">Buy Mokébox<a>
   <p style="margin: 0; padding: 0; margin-bottom: 10px, font-size: smaller">
     Use this to capture Moképon.
   </p>
 </div>
 <hr/>
 <a id="back-button" href="javascript:;" onClick="goBack()">Go back.</a>
</div>
[:div.section
   [:p (str "You walk into the shop. A midget stands behind the counter on a stool. "
            "He occasionally props himself up with locked arms and "
            "dangles his feet in the air.")]
   [:div [:a {:style {:margin "0"
                      :padding: "0"
                      :href "javascript:;"
                      :on-click "buyItem()"}}
          "Buy Mokébox"]
    [:p {:style {:margin "0"
                 :padding "0"
                 :margin-bottom "10px"
                 :font-size "smaller"}}
     "Use this to capture Moképon."]]
   [:hr]
   [:a#back-button {:href "javascript:;"
                    :on-click "goBack()"}
    "Go back."]]

[‘logEverything’, [‘doWork’, [‘sayPerson’, 5, 6], [‘toString’, 7, 8]]]

[‘doWork’, [‘log’, ‘sayPerson’], [‘sayPerson’, 5, 6], [‘log’, ‘toString’], [‘toString’, 7, 8]] macro logeverything

IR

Story

I aquired RubyMotion.

Hello World ll

; Declare the string constant as a global constant. @.str = private unnamed_addr constant [13 x i8] c”hello world\0A\00”

; External declaration of the puts function declare i32 @puts(i8* nocapture) nounwind

; Definition of main function define i32 @main() { ; i32()* ; Convert [13 x i8]* to i8 … %cast210 = getelementptr [13 x i8] @.str, i64 0, i64 0

; Call puts function to write out the string to stdout. call i32 @puts(i8* %cast210) ret i32 0 }

; Named metadata !1 = metadata !{i32 42} !foo = !{!1, !1}

LLVM Compiler

It’s taking over the world.

Kaledescope Language

C Brush Up: https://viewsourcecode.org/snaptoken/kilo/ Toy Language: https://llvm.org/docs/tutorial/ Objective C Meta Language: https://llvm.org/docs/tutorial/OCamlLangImpl1.html

C# ?

Dictionaries over Classes

Property Injection when needed over Constructor DI by Default

Feedback Loops over Testing/Debugger

Roslyn over .Net Core

Down the Stack Instead of Up?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment