简体   繁体   中英

Haskell 'Either' data type and readability?

I'm learning 'Either' data structures in Haskell and have written the following:

type PhoneBook = [(String, String)] 
createPhoneBook :: PhoneBook --Use function to generate instance of type
createPhoneBook = [("betty","1212-232"),
                   ("billy", "3443-434"),
                   ("derdre", "3232-221")]

data PresentInPhoneBook = Present | NotPresent deriving (Show, Eq) --Either 
type IsPresent = String
type IsNotPresent = String

checkPhoneBook :: String -> PhoneBook -> Either IsPresent IsNotPresent
checkPhoneBook name pb = if foldRes == True then Left "Match" else Right "No Match"
where 
    foldRes = foldl (\acc (key,value) -> if key == name then True else acc) False pb

Are there any improvements to make this code more readable?

I appreciate its a trivial example, but I'm just learning at this stage.

Is this

if foldRes == True then

by accident, or do you find it more readable than just

if foldRes then

In the latter case, I'd propose

if (foldRes == True) == True then

which must be, by extension, even more readable.

I would write it like that:

import Data.Maybe (isJust)

checkPhoneBook :: String -> PhoneBook -> PresentInPhoneBook
checkPhoneBook name pb = isJust (lookup name pb)

There is not reason for use to have checkPhoneBook return Either IsPresent IsNotPresent . Just return PresentInPhoneBook . In this case it would also be ok to return a Bool . Also take a note of lookup (that I use above). It returns a Maybe value, so you can use it to lookup a name as well as to figure out if a name exists in the phone book.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM