- 论坛徽章:
- 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
复制代码 |
|