Skip to content

Instantly share code, notes, and snippets.

@dscleaver
Created June 14, 2011 16:33
Show Gist options
  • Save dscleaver/1025282 to your computer and use it in GitHub Desktop.
Save dscleaver/1025282 to your computer and use it in GitHub Desktop.
Implementation of the Sieve of Eratosthenes in Magpie
import async
def nextFrom(channel is Channel)
ChannelIterator new(channel: channel)
end
defclass ChannelIterator
val channel is Channel
end
def (this is ChannelIterator) iterate
this
end
def (this is ChannelIterator) next
true
end
def (this is ChannelIterator) current
this channel receive
end
def count(from: from is Int)
count(from: from, by: 1)
end
def count(from: from is Int, by: step)
InfiniteRange new(from: from, by: step)
end
defclass InfiniteRange
val from is Int
val by is Int
end
def (this is InfiniteRange) iterate
InfiniteRangeIterator new(this)
end
defclass InfiniteRangeIterator
val range is InfiniteRange
var at is Int
end
def (this == InfiniteRangeIterator) init(range is InfiniteRange)
this init(range: range, at: range from)
end
def (this is InfiniteRangeIterator) next
true
end
def (this is InfiniteRangeIterator) current
val now = this at
this at = this at + this range by
now
end
import async
import lazy
import chanutils
def spawnGenerator(channel is Channel)
run with for i = count(from: 2) do channel send(i)
end
def spawnFilter(in is Channel, prime is Int)
val out = Channel new(1)
run with for i = nextFrom(in) do if (i % prime) != 0 then out send(i)
out
end
var channel = Channel new(1)
spawnGenerator(channel)
for i = 1 to(100) do
var prime = channel receive
print(prime)
channel = spawnFilter(channel, prime)
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment