免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 3884 | 回复: 5
打印 上一主题 下一主题

[haskell]问个求子串位置的程序 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2010-07-16 12:07 |只看该作者 |倒序浏览
本帖最后由 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.

  1. instance (Num a)=> Num (Maybe a) where
  2.     (Just n) + (Just m) = Just (n+m)
  3.     _+_=Nothing                          

  4. f [] s2=Nothing
  5. f s1@(x:xs) s2 = if isPrefix s1 s2 then Just 0 else (Just 1)+ (f xs s2)
  6.                  where
  7.                    isPrefix _ [] = True
  8.                    isPrefix (x:xs) (y:ys) = if x==y then isPrefix xs ys else False
  9.                    isPrefix _ _ = False
复制代码

论坛徽章:
0
2 [报告]
发表于 2010-07-17 19:44 |只看该作者
本帖最后由 SNYH 于 2010-07-17 20:16 编辑

  1. else (Just 1)+ (f xs s2)
  2. 可以改为
  3. else  fmap (+1) (f xs s2)
  4. 不需要instance
  5. Maybe 是一个典型的functor
复制代码
而且你实现的这个Num 的instance 不完全其他的几个方法没有实现会出现警告的


另外 isPrefix 在Data.List 中有一个对应的函数  Data.List.isPrefixOf

论坛徽章:
0
3 [报告]
发表于 2010-07-17 19:45 |只看该作者
再补充点
isPrefix s1 s2
一般如果是这种名字的函数写成
  s1 `isPrefix` s2  可读性是不是强点?

论坛徽章:
0
4 [报告]
发表于 2010-07-17 21:11 |只看该作者
fmap 好,改过来了。

  1. f [] s2=Nothing
  2. f s1@(x:xs) s2 = if isPrefix s1 s2 then Just 0 else fmap (+1) (f xs s2)
  3.                  where
  4.                    isPrefix _ [] = True
  5.                    isPrefix (x:xs) (y:ys) = if x==y then isPrefix xs ys else False
  6.                    isPrefix _ _ = False
复制代码
可读性那个也很有道理,不过暂时不改了。

有收获,谢谢啊。

论坛徽章:
0
5 [报告]
发表于 2010-07-17 21:28 |只看该作者
[code]fmap (+1) (f xs s2) [\code]
换成
[code]f xs s2 >>= (\x -> return (x+1))[\code]
也是差不多


一个用的functor  一个用的是monad

还可以直接使用 pattern match
比如写个
maybeAdd Nothing _ = Nothing
maybeAdd _ Nothing = Nothing
maybeAdd (Just x) (Just y) = Just (x+y)

helper function 相对来说也比 实现 一个  instance 来实现(+)要好点吧。。。。

论坛徽章:
0
6 [报告]
发表于 2010-07-17 21:48 |只看该作者
嘿嘿,再次学到,

  1. f [] s2=Nothing
  2. f s1@(x:xs) s2 = if isPrefix s1 s2 then Just 0 else (f xs s2)>>=return.(+1)
  3.                  where
  4.                    isPrefix _ [] = True
  5.                    isPrefix (x:xs) (y:ys) = if x==y then isPrefix xs ys else False
  6.                    isPrefix _ _ = False
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP