haskell monad用于模仿OO样式代码

时间:2012-01-28 01:40:23

标签: haskell haskell-platform

http://www.haskell.org/haskellwiki/State_Monad的具体示例非常有助于理解如何使用monad编写实际代码(另请参阅stackoverflow / 9014218)。但是我们大多数新生来自OO背景,因此将OO程序映射到haskell将有助于演示如何编写等效的haskell代码。 (是的,这两种范式完全不同,将OO风格的代码直接翻译成haskell是不明智的,但这只是一次作为教程。)

这是一个OO风格的代码,它创建一个对象的2个实例,然后调用修改其各自成员变量的成员函数,最后打印它们。我们如何使用haskell state monads写这个?

class A:
    int p;
    bool q;
    A() { p=0; q=False;}    // constructor
    int y() {   // member function
        if(q) p++; else p--;
        return p;
    }
    bool z() {  // member function
        q = not q;
        return q;
    }
main:
    // main body - creates instances and calls member funcs
    a1 = A; a2 = A; // 2 separate instances of A
    int m = a1.y();
    m = m + a1.y();
    bool n = a2.z();
    print m, n, a1.p, a1.q, a2.p, a2.q;

2 个答案:

答案 0 :(得分:5)

直接翻译类似于:

module Example where

import Control.Monad.State

data A = A { p :: Int, q :: Bool }

-- constructor
newA :: A
newA = A 0 False

-- member function
y :: State A Int
y = do
  b <- getQ
  modifyP $ if b then (+1) else (subtract 1)
  getP

-- member function
z :: State A Bool
z = do
  b <- gets q
  modifyQ not
  getQ

main :: IO ()
main = do
  let (m,a1) = flip runState newA $ do
      m <- y
      m <- (m +) `fmap` y
      return m
  let (n,a2) = flip runState newA $ do
      n <- z
      return n
  print (m, n, p a1, q a1, p a2, q a2)

-- general purpose getters and setters
getP :: State A Int
getP = gets p

getQ :: State A Bool
getQ = gets q

putP :: Int -> State A ()
putP = modifyP . const

putQ :: Bool -> State A ()
putQ = modifyQ . const

modifyP :: (Int -> Int) -> State A ()
modifyP f = modify $ \a -> a { p = f (p a) }

modifyQ :: (Bool -> Bool) -> State A ()
modifyQ f = modify $ \a -> a { q = f (q a) }

我可能不会打扰手动getter / setter而只使用lenses

{-# LANGUAGE TemplateHaskell, FlexibleContexts #-}
module Main where

import Control.Applicative
import Control.Monad.State
import Data.Lenses
import Data.Lenses.Template

data A = A { p_ :: Int, q_ :: Bool } deriving Show
$( deriveLenses ''A )

-- constructor
newA :: A
newA = A 0 False

-- member function
y :: MonadState A m => m Int
y = do
  b <- q get
  if b then p $ modify (+1) else p $ modify (subtract 1) 
  p get

-- member function
z :: MonadState A m => m Bool
z = do
  q $ modify not
  q get


data Main = Main { a1_ :: A, a2_ :: A, m_ :: Int, n_ :: Bool } deriving Show
$( deriveLenses ''Main )

main :: IO ()
main = do
  -- main body - creates instances and calls member funcs
  print $ flip execState (Main undefined undefined undefined undefined) $ do
    a1 $ put newA ; a2 $ put newA -- 2 separate instances of A
    m . put =<< a1 y
    m . put =<< (+) <$> m get <*> a1 y
    n . put =<< a2 z

但这不是我真正写的东西,因为我正在向后弯曲Haskell以试图模仿OO风格。所以它看起来很尴尬。

对我来说,面向对象代码的真正目的是编程到一个接口。当我使用这些类型的对象时,我可以依赖它们来支持这些方法。所以,在haskell中,我会使用类型类来做到这一点:

{-# LANGUAGE TemplateHaskell, FlexibleContexts #-}
module Main where

import Prelude hiding (lookup)
import Control.Applicative
import Control.Monad.State
import Data.Lenses
import Data.Lenses.Template
import Data.Map

class Show a => Example a where
  -- constructor
  new :: a
  -- member function
  y :: MonadState a m => m Int
  -- member function
  z :: MonadState a m => m Bool

data A = A { p_ :: Int, q_ :: Bool } deriving Show
$( deriveLenses ''A )

instance Example A where
  new = A 0 False
  y = do
    b <- q get
    if b then p $ modify (+1) else p $ modify (subtract 1) 
    p get
  z = do
    q $ modify not
    q get

data B = B { v_ :: Int, step :: Map Int Int } deriving Show
$( deriveLenses ''B )

instance Example B where
  new = B 10 . fromList $ zip [10,9..1] [9,8..0]
  y = v get
  z = do
    i <- v get
    mi <- lookup i `liftM` gets step 
    case mi of
      Nothing -> return False
      Just i' -> do
        v $ put i'
        return True

data Main a = Main { a1_ :: a, a2_ :: a, m_ :: Int, n_ :: Bool } deriving Show
start :: Example a => Main a
start = Main undefined undefined undefined undefined
$( deriveLenses ''Main )

run :: Example a => State (Main a) ()
run = do
  -- main body - creates instances and calls member funcs
  a1 $ put new ; a2 $ put new -- 2 separate instances of a
  m . put =<< a1 y
  m . put =<< (+) <$> m get <*> a1 y
  n . put =<< a2 z

main :: IO ()
main = do
  print $ flip execState (start :: Main A) run
  print $ flip execState (start :: Main B) run

现在,我可以针对不同类型runA重复使用相同的B

答案 1 :(得分:4)

State monad不能用于模拟类。它用于模拟“粘贴”到您正在运行的代码的状态,而不是“独立”状态并驻留在面向对象的类中。

如果您不想要方法重写和继承,那么最接近Haskell中的OOP类就是使用具有相关函数的记录。在这种情况下你必须要注意的唯一区别是所有“类方法”都返回新的“对象”,它们不会修改旧的“对象”。

例如:

data A =
  A
  { p :: Int
  , q :: Bool
  }
  deriving (Show)

-- Your "A" constructor
newA :: A
newA = A { p = 0, q = False }

-- Your "y" method
y :: A -> (Int, A)
y a =
  let newP = if q a then p a + 1 else p a - 1
      newA = a { p = newP }
  in (newP, newA)

-- Your "z" method
z :: A -> Bool
z = not . q

-- Your "main" procedure
main :: IO ()
main =
  print (m', n, p a1'', q a1'', p a2, q a2)
  where
    a1 = newA
    a2 = newA
    (m, a1') = y a1
    (temp, a1'') = y a1'
    m' = m + temp
    n = z a2

此程序打印:

(-3,True,-2,False,0,False)

请注意,我们必须创建新变量来存储ma1的新版本(我每次最后都添加了')。 Haskell没有语言级可变变量,因此您不应该尝试使用该语言。

可以通过使用IO引用来创建可变变量。

但请注意,以下代码在Haskellers中被认为是非常糟糕的编码风格。如果我是一名老师并且有一个学生编写这样的代码,我就不会给作业通过成绩;如果我雇用一个编写这样代码的Haskell程序员,如果他没有很好的理由来编写这样的代码,我会考虑解雇他。

import Data.IORef -- IO References

data A =
  A
  { p :: IORef Int
  , q :: IORef Bool
  }

newA :: IO A
newA = do
  p' <- newIORef 0
  q' <- newIORef False
  return $ A p' q'

y :: A -> IO Int
y a = do
  q' <- readIORef $ q a
  if q'
    then modifyIORef (p a) (+ 1)
    else modifyIORef (p a) (subtract 1)
  readIORef $ p a

z :: A -> IO Bool
z = fmap not . readIORef . q

main :: IO ()
main = do
  a1 <- newA
  a2 <- newA
  m <- newIORef =<< y a1
  modifyIORef m . (+) =<< y a1
  n <- z a2
  m' <- readIORef m
  pa1 <- readIORef $ p a1
  qa1 <- readIORef $ q a1
  pa2 <- readIORef $ p a2
  qa2 <- readIORef $ q a2
  print (m', n, pa1, qa1, pa2, qa2)

该程序与上述程序的功能相同,但具有可变变量。同样,除了非常罕见的情况外,不要写这样的代码。