Little experiments
This page contains fragments of code that I wrote to play with languages.
Most of that experiments were inspired by KM - my only friend that really plays with programming :)
S-Expressions parser in ruby
http://en.wikipedia.org/wiki/S-expression
Short, secure
def parse(expression)
def treeize(inp)
return [],[] if inp.size == 0
plus,rest = treeize(inp[1..-1])
return [], [plus]+rest if inp[0] === ')'
return [plus]+(rest[0] || []),(rest[1..-1] || []) if inp[0] === '('
return [inp[0]]+plus,rest
end
return treeize(expression.strip[1...-1].split(/\b/).collect!{|x| x.strip.gsub(/([()])([()])/){" "+$1+" "+$2+" "}.split(" ") }.flatten.reject{|x| x.size == 0})[0]
end
p parse(" (a b c(d e f ( g h ) i ( a b) ( a (b (c(d))) ) () k ) j)")
Shorter, insecure
def parse(expression)
eval(expression.gsub(/[^() ]+/){"\"#{$&}\""}.gsub(/\"\s+\"/,"\",\"").gsub(/)\s*\"/,"),\"").gsub(/\"\s*(/,"\",(").gsub(/)\s*(/,"),(").gsub(/[[]]/){"\"+$&}.gsub(/(/,"[").gsub(/)/,"]"))
end
p parse(" (a b c(d e f ( g h ) i ( a b) ( a (b (c(d))) ) () k ) j)")
Pascal triangle, haskell rulez
http://en.wikipedia.org/wiki/Pascal’s_triangle
First try:
import System.Environment
pascal :: (Num a) => [a] -> [a]
pascal [] = []
pascal [1] = [ 1 ]
pascal [x,y] = [ x+y ] ++ [ 1 ]
pascal (x:y:xs) = [ x+y ] ++ pascal(y:xs)
pasc :: (Num a) => [a] -> [a]
pasc a = [ 1 ] ++ pascal(a)
chain :: (Num a) => a -> [a] -> ( [a] -> [a] ) -> IO()
chain 0 val fn = print val
chain count val fn = do let x = fn(val)
chain (count-1) x fn
main :: IO()
main = do args <- getArgs
chain (read(args !! 0)) ([]) pasc
Second try:
import System.Environment
main :: IO()
main = do args <- getArgs
print ( ( iterate (\val -> map (\x->((fst x)+(snd x))) (zip (val++[0]) ([0]++val))) [1]) !! ( (read ( args !! 0 )) - 1 ))
