An warware: ma'auni

A cikin duniyar shirye-shirye masu aiki, ra'ayoyi sun samo asali daban-daban. Daga cikin su, 'yan kaษ—an na iya zama kamar ba zato ba tsammani kuma suna da wuyar fahimta kamar wanda za mu ษ“ata a yau - Mai aiki. Amma da zarar kun fahimci ฦ™arfinsa da sassauฦ™arsa, masu aiki za su iya sauฦ™aฦ™e hanyoyin magance matsalolin shirye-shirye masu rikitarwa.

Fahimtar Ayyuka a Haskell

A functor, a cikin Haskell, shine nau'in da ke aiwatar da aikin Mai aiki nau'in nau'i. Da gaske wani abu ne da za a iya tsara shi. Functor ya ฦ™unshi abubuwa na farko guda biyu, aikin 'fmap' da wasu dokoki waษ—anda ke tabbatar da daidaiton ษ—abi'a.

Ana amfani da 'fmap' don amfani da aiki zuwa ฦ™ima a cikin tsari ba tare da canza tsarin kansa ba. Wannan yana nufin, masu aiki suna ษ—aukar mahallin aiwatar da ayyuka yayin da suke barin mahallin ba ya tasiri. Yana ba mu damar mai da hankali kan warware matsalolin ba tare da yin cudanya da mu'amala da mahallin ba.

instance Functor Maybe where
    fmap func (Just x) = Just (func x)
    fmap func Nothing = Nothing

Dokokin Functor

Don nau'in don cancanta a matsayin mai aiki, dole ne ya cika dokoki biyu da aka sani da Dokokin Ayyuka. Waษ—annan dokokin suna kiyaye amincin tsarin da muke aiki akai.

Doka 1: Taswirar aikin ainihi akan mai aiki yakamata ya dawo da ainihin ma'aikaci - fmap = id

fmap id (Just 3)  -- Returns: Just 3
fmap id Nothing  -- Returns: Nothing

Doka ta 2: Haษ—a ayyuka guda biyu sannan taswirar aikin da aka samu akan ma'aikaci ya zama iri ษ—aya da fara taswirar aiki ษ—aya sannan taswirar wani - fmap (f . g) == fmap f . fmap g

fmap (abs . negate) (Just 5)  -- Returns: Just 5
(fmap abs . fmap negate) (Just 5)  -- Returns: Just 5

Aiwatar da Ayyuka don Magance Matsaloli

Yanzu, bari mu kwatanta yadda Functors za su iya magance matsaloli yadda ya kamata. Misali, ka ce muna da jerin yuwuwar sakamako a matsayin jerin ฦ™ima. Idan muna son haษ“aka kowane ษ—ayan, a al'ada, dole ne mu rubuta lambar tukunyar jirgi da yawa. Shigar da Ayyuka.

'fmap' na iya yin jujjuya lissafin cikin sauฦ™i, ba tare da ฦ™etare ฦ™imar komai ba da amfani da aiki kawai zuwa ฦ™ima. Duk yayin da yake riฦ™e ainihin tsari.

let maybes = [Just 1, Nothing, Just 3]
fmap (+1) <$> maybes  -- Returns: [Just 2, Nothing, Just 4]

Don haka, masu aiki suna ba da ingantacciyar hanya, mai hankali don sarrafa ฦ™ididdiga a cikin mahallin. Suna samar da wani muhimmin sashi na ikon Haskell don gudanar da ayyuka masu rikitarwa tare da sauฦ™i, ฦ™ayatacciyar lamba.

Shafi posts:

Leave a Comment