我是Haskell的新手,我只是遵循RWH上的示例。我有在第14章有以下程序問題:Haskell monad鏈接中的類型檢查錯誤
import qualified Data.Map as M
type PersonName = String
type PhoneNumber = String
type BillingAddress = String
data MobileCarrier = Honest_Bobs_Phone_Network
| Morrisas_Marvelous_Mobiles
| Petes_Plutocratic_Phones
deriving (Eq, Ord)
findCarrierBillingAddress :: PersonName
-> M.Map PersonName PhoneNumber
-> M.Map PhoneNumber MobileCarrier
-> M.Map MobileCarrier BillingAddress
-> Maybe BillingAddress
-- This will work
findCarrierBillingAddress person phoneMap carrierMap addressMap = do
phone <- M.lookup person phoneMap
carrier <- M.lookup phone carrierMap
address <- M.lookup carrier addressMap
return address
-- This will NOT work:
findCarrierBillingAddress person phoneMap carrierMap addressMap =
return person >>=
lookup phoneMap >>=
lookup carrierMap >>=
lookup addressMap
where lookup = flip M.lookup
看來,在單子寫findCarrierBillingAddres當鏈接的格式使用>> =,它只是不類型檢查:
/home/bruce/Programming/haskell/real/ch14/hello.hs:21:9:
Couldn't match type `[Char]' with `MobileCarrier'
Expected type: MobileCarrier -> Maybe BillingAddress
Actual type: PersonName -> Maybe BillingAddress
In the return type of a call of `lookup'
In the second argument of `(>>=)', namely `lookup addressMap'
In the expression:
return person >>= lookup phoneMap >>= lookup carrierMap
>>= lookup addressMap
/home/bruce/Programming/haskell/real/ch14/hello.hs:21:16:
Couldn't match type `MobileCarrier' with `[Char]'
Expected type: M.Map PersonName BillingAddress
Actual type: M.Map MobileCarrier BillingAddress
In the first argument of `lookup', namely `addressMap'
In the second argument of `(>>=)', namely `lookup addressMap'
In the expression:
return person >>= lookup phoneMap >>= lookup carrierMap
>>= lookup addressMap
Failed, modules loaded: none.
問題是......爲什麼使用>> =的第二個格式不會輸入check?
你應該把人的最後一個參數。部分應用似乎更好。你可以使用Kleisli組合重寫,<= <。 – augustss