2012-10-01 42 views
1

我正在寫一個Haskell函數,遞歸地將一個整數i與元組列表進行比較。特別是,我想比較整數i到列表中的每個a(a,b)。如果i < a然後打印與a遞歸比較一個整數到一個元組列表

樣品輸入/輸出對應

check 0.01 [(0.25, 'x'),(0.50,'y'),(0.75,'z')] = 'x' 
check 0.4 [(0.25, 'x'),(0.50,'y'),(0.75,'z')] = 'y' 
check 100 [(0.25, 'x'),(0.50,'y'),(0.75,'z')] = ' ' 

我寫了我會怎樣接近它的僞的b,但我有麻煩翻譯是僞代碼到實際的Haskell功能。以下是我迄今爲止:

check :: a -> [(a,b)] -> b 
check i (a,b):xs = tuples d xs 
    | if d <= a in (a,b) then = b //pseudocode 
    | id d !<= a in (a,b) then recursively check the next tuple //pseudocode 
    | otherwise ' ' // d is larger than all the a's of the tuple so return a space 

我相信我正在考慮的方式是正確的,但我無法弄清楚如何通過整數i相較於a S的元組遍歷元組。任何幫助?

回答

5

幾點需要注意:

  • 你不能在同一個函數返回一起許多像1和像' '字符,因爲它們是不同類型的。你可以做的事情是使用Maybe b返回Nothing你想返回' 'Just 1你想返回1

  • 由於您正在對類型a進行比較,因此您需要a屬於Ord類型的類。

所以修改後的程序變爲

check :: (Ord a) => a -> [(a,b)] -> Maybe b 
check d [] = Nothing 
check d ((a,b):xs) | d <= a = Just b 
       | otherwise = check d xs 

試行在ghci中的函數給出

> check 0.01 [(0.25, 1),(0.50,2),(0.75,3)] 
Just 1 
> check 0.4 [(0.25, 1),(0.50,2),(0.75,3)] 
Just 2 
> check 100 [(0.25, 1),(0.50,2),(0.75,3)] 
Nothing 

您還可以使用從Data.Listfind寫你的函數,它的類型爲

find :: (a -> Bool) -> [a] -> Maybe a 

所以你的功能檢查變得

check2 :: (Ord a) => a -> [(a,b)] -> Maybe b 
check2 a = fmap snd . find ((> a) . fst) 

(編輯)的變化,根據編輯的問題

check :: (Ord a) => a -> [(a,Char)] -> Char 
check d [] = ' ' 
check d ((a,b):xs) | d <= a = b 
        | otherwise = check d xs 

爲了能夠使用原來的檢查功能,您還可以使用fromMaybeData.Maybe

newCheck :: Ord a => a -> [(a, Char)] -> Char 
newCheck d xs = fromMaybe ' ' $ check d xs 
+0

好吧,這是有道理的。既然你指出他們沒有返回相同的類型,如果他們都返回Char,那麼可以這樣做。我編輯了示例輸出以反映該想法 – NuNu

+2

@NuNu給定任何固定類型,可以將此解決方案與'fromMaybe defaultValue'組合以獲得期望的結果。 'fromMaybe'函數可以從'Data.Maybe'獲得。 –

+0

@NuNu我加了你想要的。 – Satvik

相關問題