試圖寫在Haskell一個簡單的「模型 - 視圖 - 控制器」的應用程序與泛型編程的情況(只是爲了學習):在Haskell
給出的一般類型TState
TAction
TReaction
, 關鍵定義是用於變更功能的模型是
(TAction, TState) -> (TReaction, TState)
(:: TFunction_ChangeModel
)
的代碼來創建一個功能:: TFunction_ChangeModel
或函數 :: TFunction_ModelAndViewCombined
是固定並且可以很容易地推廣(當提供必要的功能時,請參閱下面的程序)。
我想(這是一個問題)擺脫必須定義 虛擬類型像type TState = Int
與一個筆記'請定製'。
因此,
可以將下面的代碼而不前三type Txxxx =
寫?
(注意:歡迎任何建議和批評)。
-- just to make this compile
type TState = Int
type TAction = Char
type TReaction = Double
-- aply an action to an state gives a new state
type TFunction_ChangeState = TState -> TAction -> TState
-- when a state is entered, a reaction is produced
type TFunction_WhatReaction = TState -> TReaction
-- the model is a function from an action and a state into a new state and a reaction
type TFunction_ChangeModel = (TAction, TState) -> (TReaction, TState)
-- given the functions for changing state and finding out what reaction is produced
-- it is straightforward to define the function for change a model
createModelChangeFunction :: TFunction_ChangeState -> TFunction_WhatReaction -> TFunction_ChangeModel
createModelChangeFunction changeState whatReaction = \(ac, st) -> let
ns = changeState st ac
re = whatReaction ns
in (re, ns)
-- show a view of a transition to a new state and the associated reaction
type TFunction_View = (TReaction, TState) -> IO()
-- change model and view functions can be easily combined
type TFunction_ModelAndViewCombined = (TAction, TState) -> IO TState
combineModelAndView :: TFunction_ChangeModel -> TFunction_View -> TFunction_ModelAndViewCombined
combineModelAndView change view = \(a, s) -> do
let (r, s') = change (a, s)
view (r, s')
return s'
--
type TFunction_ControllerLoop = TState -> TFunction_ModelAndViewCombined -> IO TState
--
main = do
print "hi"
ÿ這可能是一個選擇。謝謝。 (在C++中,我將定義模板函數,具體取決於類型tAction,tState,tReaction)。謝謝。 – cibercitizen1