- 論壇徽章:
- 0
|
本帖最后由 retuor 于 2010-07-16 12:40 編輯
做了個練習,大家給點意見。
Exercise 10. Write a function f :: String -> String -> Maybe Int
that takes two strings. If the second string appears within the first, it
returns the index identifying where it starts. Indexes start from 0. For
example,
f "abcde" "bc" ==> Just 1
f "abcde" "fg" ==> Nothing
我的想法是,如果 s2 是 s1=(x:xs) 的前綴,則返回 0,否則返回 1+ s2 在 xs 中的位置,如是遞歸下去。由于題目要求返回 Maybe 類型,最好能有 (Just 1)+(Just 1)=Just 2 之類的運算,所以寫了個 Maybe Int 的 instance.
- instance (Num a)=> Num (Maybe a) where
- (Just n) + (Just m) = Just (n+m)
- _+_=Nothing
- f [] s2=Nothing
- f s1@(x:xs) s2 = if isPrefix s1 s2 then Just 0 else (Just 1)+ (f xs s2)
- where
- isPrefix _ [] = True
- isPrefix (x:xs) (y:ys) = if x==y then isPrefix xs ys else False
- isPrefix _ _ = False
復(fù)制代碼 |
|