我是 Haskell 的新手,并不是最擅長數學的人。我得到了一項作業,其中有一點要求我們:“制作一個函式,在給定一個包含值的串列的情況下,回傳第一個值的位置,該位置大于作為引數發送的那個值。萬一沒有找到, return -1.必須使用遞回"
我想出的解決方案如下:
posicionPrecioMayorA :: [Integer] -> Integer -> Integer
posicionPrecioMayorA [] a = (-1)
posicionPrecioMayorA (x:xs) a
| x > a = 0
| otherwise = 1 posicionPrecioMayorA xs a
但它有一個主要問題,如果它沒有找到大于引數的數字,否則陳述句將繼續計數直到 [],然后在回溯中將 (-1) 添加到它。
例子:
posicionPrecioMayorA [10,15,30] 100 => 2
希望有人能幫我修復它。謝謝!
uj5u.com熱心網友回復:
您可以創建一個輔助函式并跟蹤您在遞回時所處的位置。
posicionPrecioMayorA :: [Integer] -> Integer -> Integer
posicionPrecioMayorA xs a = go xs a 0 where
go [] _ _ = -1
go (x:xs) a c
| x > a = c
| otherwise = go xs a (c 1)
uj5u.com熱心網友回復:
你說你的問題是,如果它沒有找到搜索到的元素,那么它無論如何都會向計數器加 1。嗯,這聽起來像是對問題的完美描述:您無條件地添加,您希望有條件地添加。因此,只需在您的程式中寫入一個條件,如果結果為 -1,則不要加 1:
posicionPrecioMayorA :: [Integer] -> Integer -> Integer
posicionPrecioMayorA [] a = (-1)
posicionPrecioMayorA (x:xs) a
| x > a = 0
| otherwise = case posicionPrecioMayorA xs a of
-1 -> -1
index -> 1 index
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/316809.html
標籤:哈斯克尔
