Skip to content

Instantly share code, notes, and snippets.

@rpattabi
Last active August 29, 2015 14:07
Show Gist options
  • Save rpattabi/df074927adf5d541de4f to your computer and use it in GitHub Desktop.
Save rpattabi/df074927adf5d541de4f to your computer and use it in GitHub Desktop.
Seven Languages in Seven Weeks - Io Language

Io Language

Day 2 Self-Study

1 Fibonacci

fib := method(n,
  if(n==0, 0,
     if(n==1, 1,
        fib(n-1)+fib(n-2)))
)

fib(1) # --> 1
fib(4) # --> 3

2 x/0 should return 0

origDiv := Number getSlot("/")
Number / = method(denominator,
  if(denominator==0, 0, origDiv(denominator))
)

22/0 # --> 0
22/2 # --> 11

3 Sum two-dimensional array

List sum2d := method(
  total := 0

  self foreach(r,
    r foreach(c, total = total + c))

  return total
)

2dArray := list(list(1, 2, 3), list(1, 2, 3), list(1, 2, 3))
2dArray sum2d # --> 18

5 Raise exception if list is not number only

NotNumberOnlyListError := Error clone

List sum2d := method(
  total := 0

  self foreach(r,
    r foreach(c, 
      if(c type == Number,
        total = total + c,
        Exception raise(NotNumberOnlyListError)
      )
    )
  )

  return total
)

l := list("junk", "oh ho")
l sum2d # --> NotNumberOnlyListError

6 Create type for two-dimensional matrix

Matrix := List clone

Matrix dim := method(x, y,
  for(i, 0, y-1,
    self append(List clone)
    for(j, 0, x-1,
      self at(i) append(0)
    )
  )
)

Matrix set := method(x, y, value,
  self at(y) atPut(x, value)
)

Matrix get := method(x, y,
  return self at(y) at(x)
)

myMatrix := Matrix clone
myMatrix dim(4,4)

myMatrix set(1,1, "ding")
myMatrix set(1,2, "dong")

myMatrix get(1,1) println # --> "ding"
myMatrix get(1,2) println # --> "dong"

6 Matrix transpose

Matrix transpose := method(
  t := Matrix clone
  x := self at(0) size
  y := self size
  t dim(y, x)

  for(i, x-1, 0, -1,
    for(j, y-1, 0, -1,
      t set(i, j, self get(j, i))
    )
  )

  return t
)

Matrix print := method(
  x := self at(0) size
  y := self size

  for(i, 0, y-1, 
    "" println
    for(j, 0, x-1,
      " " print
      self get(i, j) print
    )
  )

  "" println
)

myMatrix := Matrix clone
myMatrix dim(4,4)

myMatrix set(1,1, "ding")
myMatrix set(1,2, "dong")

"original" println
"--------" println
myMatrix print

transposed := myMatrix transpose
"transposed" println
"----------" println
transposed print

result := myMatrix get(1,2) == transposed get(2,1)
result println #--> true

Alternative Answers

@rpattabi
Copy link
Author

Question: How to check if something is a Number? E.g.

MyNumber := Number clone
num := MyNumber clone
num type == Number # Does not work since num type returns MyNumber

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