2015-10-12 39 views
0

我正在實現一個使用anotherFunction的函數myFunction獲取Haskell中Maybe的值

anotherFunction是一個無法修改的外部函數。它返回一個Maybe類型的值。

myFunction是遞歸函數,用於檢查另一個myFunction返回的值是Just值還是Nothing。如果是Nothing則返回Nothing,否則將使用myFunction返回的純值作爲參數anotherFunction

基本上是這樣的:

--These cannot be modified 

data A = B | F a 

anotherFunction :: x -> Maybe x 
--Something here 

myFunction :: A -> Maybe x 

--These can be modified 
myFunction (F a) = {- if (myFunction a == Nothing) 
         then Nothing 
         else anotherFunction (pure value of (myFunction a)) -} 

如何才能實現這一目標?

+3

使用case語句。在Haskell中正常函數(不是構造函數)中的 – user1937198

+2

通常以小寫字母開頭。 – jakubdaniel

+1

不僅____它們通常以小寫字母開頭,它們必須以小寫字母開頭才能在Haskell中允許。我相應地編輯了這個問題。 - - (原則上,下劃線也可以作爲變量名的第一個字符,但不要這樣做 - [下劃線有特殊含義](http://stackoverflow.com/questions/21282515/is- – leftaroundabout

回答

2

可以搭配使用caseMyFunction返回值:

case (myFunction a) of 
    Nothing -> Nothing 
    Just x -> anotherFunction x 

但是一個更簡潔的方法是使用>>=

(>>=) :: Maybe a -> (a -> Maybe b) -> Maybe b 
myFunction (f a) = (myFunction a) >>= anotherFunction 

,或者您可以使用do符號:

myFunction (f a) = do 
    x <- myFunction a 
    anotherFunction x 
2

除非簽名中有約束條件Eq a => Maybe a,否則您將無法使用==。做這類事情的最好方法是使用case聲明:

case m of 
    Just x -> anotherFunction x 
    Nothing -> Nothing 

這種模式是Maybe如此普遍,它形成了Monad實例Maybe,給你的功能return x = Just xf >>= x = case x of Just a -> f a; Nothing -> Nothing

+1

不要把它稱爲'也許',這是Prelude函數的名字 – Zeta

+0

@Zeta謝謝你,改變了。 –

1

Suppo如果您有fg,它們都會生成包裝在MaybeJust 3Just "three",Nothing)類型中的值。您可以撰寫兩個這樣的:

import Control.Monad 

f :: a -> Maybe b -- suppose these two are signatures of the given two functions 
g :: b -> Maybe c 

h :: a -> Maybe c -- this is the way you pass values from one 
h = f >=> g  -- to the other and bail out when you see Nothing 

我已經使用便於記憶的名稱爲類型ab,並c使組合物更加清晰,但要注意的是,類型不約束,在一個a簽名無關在另一個簽名中使用a,實際類型是在兩個函數在具體上下文中使用時決定的。

由於您似乎沒有對aF a構造函數進行任何約束,我想您希望它可能與A不同。在這種情況下,函數myFunction不能有類型A -> ...,因爲您試圖通過a作爲參數。