Skip to content

Instantly share code, notes, and snippets.

@g-leech
Last active July 22, 2018 16:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save g-leech/fc8b9ccc6bbc84a8c8ac59a1c2e7f48f to your computer and use it in GitHub Desktop.
Save g-leech/fc8b9ccc6bbc84a8c8ac59a1c2e7f48f to your computer and use it in GitHub Desktop.
##################################
## DAY 1
# Evaluate 1 + 1 and then 1 + "one". Is Io strongly typed or weakly typed?
1 + 1
1+"one"
# > Exception: argument 0 to method '+' must be a Number, not a 'Sequence'
# Io is Strong: it does not perform implicit casts between types.
############################################################
# Is 0 true or false?
0 and true
# ==> true
0 or false
# ==> true
0 == true
# ==> false
# .: 0 is equivalent to `true` without being identical.
# What about the empty string?
"" and true
# ==> true
"" or true
# ==> true
"" == true
# ==> false
# Same story
# Is nil true or false?
nil and true
# ==> false
nil or false
# ==> false
nil == true
# ==> false
# So `nil` is not true in any sense.
############################################################
# How can you tell what slots a prototype supports?
Object slotNames
# ==> list(or, coroDo, ifError, handleActorException, do, inlineMethod, -, isIdenticalTo, slotNames, become, actorProcessQueue, removeProto, asBoolean, markClean, contextWithSlot, argIsActivationRecord, deprecatedWarning, removeAllSlots, launchFile, super, yield, setProtos, evalArgAndReturnSelf, returnIfError, print, ownsSlots, continue, asyncSend, evalArgAndReturnNil, removeAllProtos, in, doString, compare, serialized, isKindOf, <=, setSlot, cloneWithoutInit, serializedSlots, isError, protos, returnIfNonNil, resend, thisContext, coroFor, evalArg, switch, memorySize, isLaunchScript, hasLocalSlot, @, thisMessage, raiseIfError, ancestorWithSlot, while, type, block, , hasSlot, performWithArgList, pause, ifNil, clone, try, asSimpleString, ==, writeln, not, relativeDoFile, .., ifNonNil, getSlot, slotSummary, uniqueHexId, <, init, shallowCopy, wait, justSerialized, proto, lexicalDo, foreachSlot, uniqueId, slotDescriptionMap, for, return, coroWith, argIsCall, serializedSlotsWithNames, >, perform, >=, doRelativeFile, setSlotWithType, stopStatus, ancestors, @@, println, break, appendProto, isNil, asString, ifNilEval, getLocalSlot, isActivatable, hasProto, doMessage, if, slotValues, coroDoLater, list, futureSend, lazySlot, message, currentCoro, and, write, method, setIsActivatable, !=, ?, apropos, loop, thisLocalContext, addTrait, setProto, ifNonNilEval, updateSlot, actorRun, isTrue, removeSlot, newSlot, hasDirtySlot, doFile, prependProto)
# ; This language is not THAT simple.
###############################################################################
# What is the difference between = (equals), := (colon equals), and ::= (colon colon equals)?
# := creates slot and assigns a value
a := 1
# == newSlot("a", 1)
# = assigns a value in a slot that already exists
a = 2
b = 3
# == updateSlot("a", 2)
# ::= creates a slot, a setter, and assigns a value
b ::= 1
setB(3)
######################################################
# Run an Io program from a file.
# io f.io
######################################################
# Execute the code in a slot given its name.
Detective := Object clone do(
deduce := method("aha!" print)
)
holmes := Detective clone
givenItsName := "deduce"
holmes getSlot(givenItsName) call
##################################
## DAY 2
# Write a program to find the nth Fibonacci number. solve the problem with recursion
fib := method(n,
if (n < 1, Exception raise(n .." is not a valid index!"))
if (n < 3, return 1)
else ( return (fib(n-1) + fib(n-2) )
)
# and with loops.
loop := method(n,
first := second := 1;
for( 0, 1, n-1,
acc := first + second;
first = second;
second = acc;
)
(return first)
)
# How would you change / to return 0 if the denominator is zero?
realDiv := Number getSlot("/")
Number / = method( divisor, if (divisor == 0, 0, realDiv(divisor)) )
# Write a program to add up all of the numbers in a two-dimensional array.
matrix := list(list(1, 1, 2), list(3, 5, 8), list(13, 21, 34))
sum2d := method(m, m flatten sum)
# Add a slot called myAverage to a list that computes the average of all the numbers in a list. What happens if there are no numbers in a list? (Bonus: Raise an Io exception if any item in the list is not a number.)
List myAverage := method( if (size > 0,
(return sum / size),
Exception raise("Can't avg emptiness") )
)
list(55, 89, 144) myAverage
list(55, 89, "a") myAverage # already throws an exception
list() myAverage
# Write a prototype for a two-dimensional list.
# The dim(x, y) method should allocate a list of y lists that are x elements long.
# set(x, y, value) should set a value,
# get(x, y) should return that value.
# Write the matrix to a file
List2d := List clone do(
(dim := method(x, y,
self setSize(x);
for (i, 0, (x - 1), 1,
self atPut( i, (list setSize(y)) )
)
))
(get := method (x, y,
return self at(x) at(y)
))
(set := method (x, y, value,
self at(x) atPut(y, value);
return self
))
(save := method (file,
File with(file) open write(self serialized) close
))
)
2d := List2d clone dim(3,4)
for( i, 0, 2,
2d set(i, i, i)
)
2d save("mat.dat")
##########################################################
# Write a program that gives you ten tries to guess a random number from 1--100.
rand := (Random value(100) floor) + 1
reader := File standardInput
i := 0
while( i < 10,
guess := reader readLine("Guess: ") asNumber;
if (guess isNan, Exception raise("NaN!"));
if( rand == guess,
"Ye that's the one" println;
break
);
i := i + 1;
)
##################################
## DAY 3
# Enhance the XML program to add spaces to show the indentation structure.
Builder := Object clone do(
(depth ::= 0)
(indent := " ")
(spaces := method( indent repeated(depth) ))
(print_spaced := method( arg,
content := doMessage( arg );
if ( content != nil, writeln(spaces, content) );
))
(shift_depth := method(offs, setDepth( depth + offs )))
(tag := method(name, closer, writeln(spaces, "<", closer, name, ">") ))
(forward := method(
reflection := call message() name();
tag(reflection, "");
shift_depth(1);
call message() arguments() foreach( arg,
print_spaced(arg)
);
shift_depth(-1);
tag(reflection, "/");
))
)
Builder ul( li("Io"), li("Lua"), li(div("fuck io"), "Javascript"), li("Lisp") )
##########################################
# Create a list syntax that uses brackets.
# Assume he means curlies. Another methodMissing trick: vals are args passed to curlyBrackets.
# Convert args to vals, then map them to a List:
curlyBrackets := method(
call message arguments map( arg, doMessage(arg) );
);
{ "a", "b", "c" }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment