File: RebindableSyntax.hs

package info (click to toggle)
haskell-ghc-exactprint 1.7.1.0-1
  • links: PTS
  • area: main
  • in suites: forky, sid, trixie
  • size: 6,044 kB
  • sloc: haskell: 32,076; makefile: 7
file content (60 lines) | stat: -rw-r--r-- 1,007 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
{-# LANGUAGE RebindableSyntax, NoMonomorphismRestriction #-}

-- From https://ocharles.org.uk/blog/guest-posts/2014-12-06-rebindable-syntax.html

import Prelude hiding ((>>), (>>=), return)
import Data.Monoid
import Control.Monad ((<=<))
import Data.Map as M

addNumbers = do
  80
  60
  10
  where (>>) = (+)
        return = return

(>>) = mappend
return = mempty

-- We can perform the same computation as above using the Sum wrapper:

someSum :: Sum Int
someSum = do
    Sum 80
    Sum 60
    Sum 10
    return

someProduct :: Product Int
someProduct = do
    Product 10
    Product 30

-- Why not try something non-numeric?

tummyMuscle :: String
tummyMuscle = do
    "a"
    "b"


ff = let
  (>>)    = flip (.)
  return  = id

  arithmetic = do
      (+1)
      (*100)
      (/300)
      return

  -- Here, the input is numeric and all functions operate on a number.
  -- What if we want to take a list and output a string? No problem:

  check = do
      sum
      sqrt
      floor
      show
  in 4