网络书屋(Web Reading Room)

A blogging framework for hackers.

Haskell-one-line

Haskell have many beautiful features,such as monad(combination),so we can write very elegant code(compact code).

Reference Here verbose:

1
2
3
4
5
6
7
8
9
10
module Main where

import System.IO

main = do
  theInput <- readFile "input.txt"
  putStrLn (countLines theInput)

countLines :: String -> String
countLines str = (show (length (lines str)))

elegant:

1
2
3
4
5
6
module Main where

import System.IO

main = readFile "input.txt" >>= print.length.lines
  

Function Application

verbose:

1
2
not (odd 4)
not $ odd 4

elegant: The . Function It composes functions in a readable manner

1
2
3
4
f(g(h(k(x)))) is ugly
(f.g.h.k)(x) is pretty
 (not.odd) 4
 (length.head.words) "University of Virginia"

上面写的elegant风格都可以叫做point-free风格,它使用Monad的结合律,

比如下面转换一般代码到point-free风格的方法:

1
2
3
4
5
6
7
8
9
f x = 5 + 8/x
f x = (+) 5 (8/x)
f x = (+) 5 ((/) 8 x)
f x = ((+) 5) ((/) 8 x)
f x = ((+) 5) (((/) 8) x)
f x = ((+) 5).(((/) 8)) x

f= ((+) 5).((/) 8)
f= (5+).(8/)

另一个常用的转换写法:

1
2
add a b = a+ b  ---> add =(+)
f s =length (head (words s)) ---> f= length.head.words

Add later