[英]Can I use let in guards on Haskell?
現在我有一個錯誤,說輸入'|'上的解析錯誤 指的是'|' 在if語句之前。 我也不確定我是否可以像下面的代碼那樣使用let in guard。 下面的代碼是我的問題的一個例子,請幫助糾正我的錯誤,提前謝謝!
func x y
| let
sum = x + y
mult = x * y
| if sum == 3
then do
sum+=1
else if mult == 5
then do
mult -=1
實際上,Haskell2010允許let
表達式出現在后衛中。 請在此處查看報告。 |let decls
將decls
定義的名稱引入環境。
對於你的情況,我們可以寫
fun x y
| let sum = x + y, sum == 3 = Just (sum + 1)
| let mult = x * y, mult == 5 = Just (mult - 1)
| otherwise = Nothing
不幸的是,我們不能做到這一點與let
。
更確切地說,我們可以寫
func x y | let z = .. in condition = result
| otherCondition = otherResult
但z
將只在可見的condition
,而不是result
, otherCondition
或otherResult
。
(這可以通過使用模式警衛得到改善,但不完全: z
仍然不可用在otherCondition
和otherResult
)
解決方案是where
使用:
func x y | condition = result
| otherCondition = otherResult
where z = ...
在這里, z
隨處可見。
(就個人而言,我不喜歡這種形式where
因為它離z
的使用太遠了,但在這種情況下我看不到任何簡單的替代方案。)
最后,讓我補充一點,你的代碼對我來說看起來不起作用: if then
沒有函數編程中的else
if then
沒有了,而mult -= 1
不能修改變量mult
(對於sum += 1
)。
您可以在頂部使用let
,但必須后跟in
以指定要使用定義值的塊。 如果sum /= 3
和mul /= 5
你也錯過了該做什么的條件。 所以可能會返回一個Maybe
類型可能會更好,例如
func :: Integral a => a -> a -> Maybe a
func x y = let sum = x + y
mul = x * y
in case (sum, mul) of
(3, _) -> Just (sum + 1)
(_, 5) -> Just (mul - 1)
_ -> Nothing
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.