2012-01-01 83 views
9

代碼的下面片段是在創建函數generateUpTo其生成列表pAllSorted取決於n最大因此RMAX嘗試的一部分。Haskell中 - 在範圍上並不

nmax = rmax `div` 10 

pass = rmax `elem` mot 
fail = rmax `notElem` mot 

generateUpTo rmax = check rmax 
where 
     check pass = pAllSorted 
     check fail = error "insert multiple of 10!" 

但是,試圖編譯時,編譯器爲約RMAX一個「不在範圍內」的錯誤(什麼是這裏)行1,3和4

(如何)我可以離開rmax undefined直到使用generateUpTo函數?

+7

對於一直投票Haskell初學者問題的人來說,如果你能知道,請留下評論,告訴你爲什麼要這樣做。 – Phyx 2012-01-01 16:49:38

+1

我們會外出給他投票的! :)更嚴重的是,對於那些問我「爲我工作」的作業問題的人來說,存在着很多的濫用,也許這是一個錯誤。 – gatoatigrado 2012-01-01 22:41:13

+1

@Phyx事實上,我儘量不要投新手問題,但也許我可以解釋downvoter。這些問題中的大部分都是「過於本地化」的用語,更一般地說,這些用語並不有趣。 – 2012-01-01 23:40:04

回答

9

如果你想使用rmaxnmaxpassfail沒有把它當作一個arguement,你需要把它列入的generateUpTowhere塊。否則,它的字面意思是「不在範圍內」。例如:

generateUpTo rmax = check rmax 
    where 
     check pass = pAllSorted 
     check fail = error "insert multiple of 10!" 
     nmax = rmax `div` 10 
     pass = rmax `elem` mot 
     fail = rmax `notElem` mot 

如果你想在多個地方使用這些功能,你可以只accect RMAX作爲arguement:

nmax rmax = rmax `div` 10 
pass rmax = rmax `elem` mot 
fail rmax = rmax `notElem` mot 

注意 - 它看起來像你也有一些問題,你的定義check ... passfail值只有check的爭論,而不是你上面定義的函數。

更新

使用n最大(外最,其中塊範圍的版本),你需要RMAX的值傳遞給它。像這樣:

nmax rmax -- function application in Haskell is accomplished with a space, 
      -- not parens, as in some other languages. 

但是請注意,在nmax定義名稱rmax不再顯著。這些功能都是完全一樣的:

nmax rmax = rmax `div` 10 
nmax a = a `div` 10 
nmax x = x `div` 10 

同樣,你不需要有一個名爲rmax值來調用它。

nmax rmax 
nmax 10 -- this is the same, assuming rmax is 10 
nmax foo -- this is the same, assuming foo has your 'rmax' value. 
+0

如果在其他地方定義** pAllsorted **,並且在該定義中使用** nmax **,那麼如果我使用此方法解決問題,** nmax **是否仍然在範圍內? – 2012-01-01 16:47:04

+0

在我的第二個例子中......是的,這應該在'where'塊之外工作。要調用它,你需要傳遞rmax的值。例如:'nmax 10'或'nmax myRmaxVal' – 2012-01-01 16:49:15

+0

您能澄清一下如何將rmax的值傳遞給它嗎? – 2012-01-01 16:53:19

4

只要把的nmaxpassfail定義成generateUpTowhere條款,就像你check一樣。

2
nmax rmax = rmax `div` 10 

pass rmax = rmax `elem` mot 
fail rmax = rmax `notElem` mot 

generateUpTo rmax = check rmax 
where 
    check pass = pAllSorted 
    check fail = error "insert multiple of 10!" 

的Rmax爲函數參數則在聲明它的功能之外未定義的。在這個例子中,函數nmax中的rmax與generateUpTo中的rmax完全無關。