Skip to content

Instantly share code, notes, and snippets.

@lojic
Last active December 19, 2015 03:48
Show Gist options
  • Save lojic/5892340 to your computer and use it in GitHub Desktop.
Save lojic/5892340 to your computer and use it in GitHub Desktop.
module MicroBlogger
def self.start
loop do
printf "enter command: "
Cmd.execute(gets.chomp)
end
end
module Cmd
def self.commands
[ [ lambda {|s| s == 'q' }, lambda { puts 'Goodbye'; exit(0) } ],
[ lambda {|s| s == 'tweet'}, lambda { puts 'tweeting' } ],
[ lambda {|s| s == 'dm' }, lambda { puts 'direct messaging' } ],
[ lambda {|s| s == 'help' }, lambda { puts 'helping' } ],
[ lambda {|s| true }, lambda { } ] ]
end
def self.execute input
commands.find {|match, _| match.call(input) }[1].call
end
end
end
MicroBlogger.start
# as compared to the original refactoring of:
class MicroBlogger
def start
command = ""
while command != "q"
printf "enter command: "
command = gets.chomp
process(command)
end
end
class DirectMessageCommand
def match?(input)
input == "dm"
end
def execute
puts "direct messaging"
end
end
class HelpCommand
def match?(input)
input == "help"
end
def execute
puts "helping"
end
end
class NoActionCommand
def match?(input)
true
end
def execute
# no-op
end
end
class QuitCommand
def match?(input)
input == "q"
end
def execute
puts "Goodbye"
end
end
class TweetCommand
def match?(input)
input == "tweet"
end
def execute
puts "tweeting"
end
end
def commands
quit = QuitCommand.new
tweet = TweetCommand.new
dm = DirectMessageCommand.new
help = HelpCommand.new
no_action = NoActionCommand.new
[ quit, tweet, dm, help, no_action ]
end
def command_for_input(input)
commands.find {|command| command.match?(input) }
end
def process(input)
command_for_input(input).execute
end
end
MicroBlogger.new.start
import Data.List
commands = [ (\ s -> s == "q", putStrLn "Goodbye" ),
(\ s -> s == "tweet", putStrLn "tweeting" ),
(\ s -> s == "dm", putStrLn "direct messaging" ),
(\ s -> s == "help", putStrLn "helping" ),
(\ s -> True, return () ) ]
execute input = action where
Just (match,action) = find (\ (m,e) -> m input) commands
main = do
putStrLn "enter command: "
input <- getLine
execute input
if input == "q" then return () else main
import System; import Data.Char
process input | input == "q" = do putStrLn "Goodbye"; exitWith ExitSuccess
| input == "tweet" = putStrLn "tweeting"
| input == "dm" = putStrLn "direct messaging"
| input == "help" = putStrLn "helping"
| foo input = bar -- Example showing logic factored out
| otherwise = return ()
where foo s = (sum (map (\ c -> ord c) s)) > 300
bar = do putStrLn "line one"
putStrLn "line two"
main = do putStrLn "enter command: "
getLine >>= process
main
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment