Daniel’s Blog

Ruby & Haskell Example

March 8th, 2007 by daniel

Ruby

(taken from https://www.ruby-lang.org/en/about/ )

#This turns an array of names into an array of URLs (but keeps it all string)
search_engines =
%w[Google Yahoo MSN].map do |engine|
"https://www." + engine.downcase + ".com"
end

The bit between do and end in the above is called a block in the Ruby Programming Language.

Haskell

So lets do the same thing in Haskell (this is written by me!)

-- this returns a URL for a given string (also makes it lowercase)
search_engine_URL :: [String] -> [String]
search_engine_URL engine = concat("https://www.", (map (toLower) engine), ".com")

and then at the Hugs/Helium prompt we ask:

map search_engine_URL ["Google", "Yahoo", "MSN"]

The two systems…

… aren’t two dissimilar really. The main point of interest is the keyword map, which is a function in both languages (well, in Ruby its technically a method on the array class), in Haskell this is a higher order function - can we call it a higher order function in Ruby???. The other point of interest is that Ruby has blocks/closures which can also be found in functional programming languages.
Ruby takes a lot of its ideas from LISP, so no wonder we can do the same sorts of things in Ruby and other Functional Programming Languages.

Let me know if you can think of an even easier/shorter way of doing it in either language.

Daniel

Technorati Tags: Haskell, Ruby, functional, programming

1 Comment

<!--<div id="semanticbrowsing" style="text-align:center;"> OpenLink RDF Browser 1 OpenLink RDF Browser 2 <area shape="rect" coords="242,5,346,102" href="https://dataviewer.zitgist.com/?uri=https://www.vanirsystems.com/danielsblog/2007/03/08/ruby-haskel