[英]creating my own module and types doesnt work as expected
我正在嘗試使用模塊制作 haskell 程序並創建自己的類型來模擬選舉:到目前為止,我有這個:
module Election
( nactionCreate
, getState
, addVotesToState
, nactionAddVotes
, stateWinner
, electionWinner
) where
-- Types Created
data Candidate = A | B deriving (Eq, Show)
type State = (String, Int, Int, Int) --deriving (Eq, Show, Read)
name :: State -> String
name (name, _, _, _) = name
representativesNumber :: state -> Int
representativesNumber (_, representativesNumber, _, _,) = representativesNumber
aVotes :: State -> Int
aVotes (_, _, aVotes, _) = aVotes
bVotes :: State -> Int
bVotes (_, _, _, bVotes) = bVotes
type Naction = [State]
-- Create a Naction From a tuples List for each State at the beginning of Election. In the beginnig each candidate has 0 votes
nactionCreate:: [(String,Int)] -> Naction
nactionCreate ((n,r):xs) = [State | name <- n, representativeNumber<-r, 0, 0]
-- Return the State with the name equal to the String. Don't exists states with equals name
getState :: Naction -> String -> State
getState [] _ = null
getState ((n,_,_,_):xs) s =
| n == s = State
| otherwise = getState xs s
-- TODO
addVotesToState :: State -> Int -> Int -> State
-- TODO
nactionAddVotes :: Naction -> [(String, Int, Int)] -> Naction
-- TODO
stateWinner :: State -> Candidate
-- TODO
electionWinner :: Naction -> Candidate
但我很難知道如何操作 mas 數據/類型。 就像在nactionCreate
中一樣,它的工作方式如下:
> naction0 =createNaction [("North",4), ("Central",6), ("West",3)]
然后我應該能夠做到:
> north0 = getState naction0 "North"
> representativesNumber north0
4
> aVotes north0
0
> bVotes north0
0
我知道我已經制作的 function 不正確(我的意思是我懷疑)但我不明白為什么或如何使用......有人可以幫助我嗎?
PS:我不想幫助我尚未嘗試制作的功能。
您的getState
實際上並沒有創建State
類型的值; 您只是在無法使用的地方使用類型構造函數。 您收到錯誤消息,因為沒有名為State
的數據構造函數。 您想返回名稱為n
的值。
也沒有像null
這樣的值。 您希望返回類型為Maybe State
,使用Nothing
表示失敗並使用Just
包裝成功匹配。
getState :: Naction -> String -> Maybe State
getState [] _ = Nothing
getState (state@(n,_,_,_):xs) s =
| n == s = Just state
| otherwise = getState xs s
這里的名稱state
是指整個State
值列表的頭部,這樣您就不必捕獲和重復元組中的所有值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.