Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS 

Simple Haskell script for word counting

This is just a simple piece of code I put together to play with some Haskell when I realised I've not been writing nearly enough of the stuff.

It reads text from stdin and prints the words it finds together with how many times each one occurred.

module Main
where

import List
import Control.Arrow

type Comparator a = (a -> a -> Ordering)

ascending :: (Ord a) => (b -> a) -> Comparator b
ascending f x y = compare (f x) (f y)

descending :: (Ord a) => (b -> a) -> Comparator b
descending = flip . ascending

secondary :: Comparator a -> Comparator a -> Comparator a
secondary f g x y = case f x y of {
                    EQ -> g x y;
                    z  -> z; }

-- Returns a list of unique elements together with their frequency. Listed in decreasing order of frequency, followed by
increasing order of the elements.
count :: (Ord a) => [a] -> [(a, Int)]
count = map (head &&& length) . sortBy (descending length `secondary` ascending head) . group . sort

main :: IO ()
main = interact $ unlines . map (\(x, y) -> (take 20 $ x ++ repeat ' ')  ++ " : " ++ show y) . count . words

Odd numbers up to 1..100 in Ruby

// 10 different ways to display odd numbers 1 through 100 in Ruby

100.times do |i|
  next if i % 2 == 0
  puts i
end

50.times { |i| p i*2+1 }
(1..100).step(2) { |i| puts i}
1.upto(100) { |i| puts i unless i[0].zero? }
puts Array.new(50) { |i| i * 2 + 1 }
# a self referential recursive lambda :-)
lambda { me = lambda { |x| p x; me.call(x+2) if x < 99 } ; me.call(1) }.call

# same thing, but passing the lambda around
rec = lambda { |v,l| p v; l.call(v+2,l) if v < 99 }
rec.call(-1,rec)

# same recursive algorithm, but in method form
def odds(x=1)
  p x
  odds(x+2) if x < 99
end
odds

class Integer
  def odd?
    self[0].nonzero?
  end
end
100.times { |i| puts i if i.odd? }


require 'delegate'
class OddNum < DelegateClass(Fixnum)
  def initialize(value)
    value |= 1  # force it odd
    super(value)
  end
  
  def succ
    # note that the delegated succ gets called when we call super
    # and the constructor forces it (up) to the next odd number
    OddNum.new(super)
    
    # or
    # OddNum.new(self + 1)  # still using the constructor's force to odd
    # or 
    # OddNum.new(self + 2)  # being odd all on our own
  end
end
(OddNum.new(1)..100).each { |i| puts i }
« Newer Snippets
Older Snippets »
Showing 1-2 of 2 total  RSS