簡體   English   中英

創建我自己的模塊和類型沒有按預期工作

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM