Lisplog

Blogging in Lisp

Search

My First Haskell Program

Submitted by Bill St. Clair on Fri, 07 Oct 2016 05:08:55 GMT

I've been working through Learn You a Haskell for Great Good, after spending quite a bit of time learning Elm, and realizing that it is basically a subset of Haskell that compiles to JavaScript.

I wrote my first tiny Haskell program. It matches one of my early Lisp programs, way back in 1974, that printed the 120 permutations of the MIT slogan: "I hate this fucking place!"

Permutation is much clearer in Haskell. And lazy computation is incredibly neat.

You can download it at lisplog.org/print-ihftp.hs or display it at lisplog.org/print-ihtfp.hs.txt. Full text below:

--
-- print-ihtfp.hs
--
-- Build with:
--   ghc --make print-ihtfp
-- Run with:
--   ./print-ihtfp
--
-- Or, in ghci:
--  :l print-ihtfp
--  main
--

import Data.Char (toUpper)

distribute :: a -> [a] -> [[a]]
distribute x [] = [[x]]
distribute x (y:ys) =
  (x:y:ys) : (map (y:) $ distribute x ys)

permute :: [a] -> [[a]]
permute [] = []
permute [x] = [[x]]
permute (x:xs) =
  concatMap (distribute x) (permute xs)

permuteSentence :: String -> [String]
permuteSentence x =
  map unwords $ permute $ words x

nums :: [String]
nums = map (++ ": ") $ map show [1..]

fixSentence :: String -> String
fixSentence "" = ""
fixSentence (x:xs) =
  (toUpper x) : xs ++ "!"
  
ihtfp :: [String]
ihtfp = permuteSentence "I hate this fucking place"

main = do
  putStrLn $ unlines $ zipWith (++) nums $ map fixSentence ihtfp

Add comment   Edit post   Add post

Comments (2)

Tweeted

Submitted by Bill St. Clair on Fri, 07 Oct 2016 11:37:12 GMT

Tweeted here.

Edit comment

Not Fair to Elm

Submitted by Bill St. Clair on Fri, 07 Oct 2016 12:51:20 GMT

I'm not being fair to Elm. It is not just Haskell.js. It contains a run-time and libraries that make creating error-free client-side web applications very easy. Bravo, Evan Czaplicki and friends.

Edit comment

Add comment   Edit post   Add post

Previous Posts:

Karabiner-Elements for macOS Sierra
macOS 10.12 Sierra
Sizing An iOS Custom Keyboard for Scaled Apps
Conway's Life in JavaScript
Mac OS X 10.11.4 Beachball on Wake from Sleep
Google Authenticator, in Your Web Browser
Another Old Friend
Firefox Discontinuing Tab Groups
Barlow's Declaration Turns Twenty
Hello Again Old Friend