2012-05-08 46 views
2

嗨,我是新來的Haskell和我試圖實現以下,我不能完全得到它的權利在功能和返回錯誤的變量在Haskell

這裏是別人聰明設置限制我想要做的基本算法可以說你有

--define some basic example function 
fun x y = x + y 
--pseudo code for what i am trying to do 
    x >= -1.0 || x <= 1.0 --variables x must be within this range else ERROR 
    y >= 1.0 || y <= 2.0 --variables y must be within this range else ERROR 

回答

5

一個非常簡單的方法來做到這一點如下。這將使用guard

fun x y 
    | x < -1.0 || x > 1.0 || y < 1.0 || y > 2.0 = error "Value out of range" 
    | otherwise = x + y 

See here一系列的日益複雜和精密的方式來報告和處理錯誤。

有時,如ivanm指出的那樣,Maybe類型更可取。這裏是一個完整性的例子:

fun' :: Float -> Float -> Maybe Float 
fun' x y 
    | x < -1.0 || x > 1.0 || y < 1.0 || y > 2.0 = Nothing 
    | otherwise = Just (x + y) 
+4

一般來說,最好是使用'Maybe'而不是'error'。 – ivanm

+0

@ivanm:取決於調用者是否「容易」預測。例如,如果一個函數的參數總是肯定的,那麼拋出一個異常是合理的,如果不是這樣的話,而不是期望調用者在每次使用該函數時處理'Maybe'。對於解析器這樣的解析器來說,解析失敗可能在任何地方合理地發生,當然,''也許''或者類似的東西肯定是要走的路。 – MathematicalOrchid

+1

@ivanm,你是對的 - 我保持簡單,但我添加了一個完整的例子。 – senderle