小弟有几个Haskell问题想问大神第一个是如何将一个列表拆开就像这样:> :type splits splits ::[a] -> [([a],[a])]> splits [1..4] [([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])]> splits "xyz" [("x","yz"),("xy","z")]> splits [True,Fa
来源:学生作业帮助网 编辑:六六作业网 时间:2024/12/04 02:46:32
小弟有几个Haskell问题想问大神第一个是如何将一个列表拆开就像这样:> :type splits splits ::[a] -> [([a],[a])]> splits [1..4] [([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])]> splits "xyz" [("x","yz"),("xy","z")]> splits [True,Fa
小弟有几个Haskell问题想问大神
第一个是如何将一个列表拆开就像这样:
> :type splits
splits ::[a] -> [([a],[a])]
> splits [1..4]
[([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])]
> splits "xyz"
[("x","yz"),("xy","z")]
> splits [True,False]
[([True],[False])]
> length (splits [1..50])
49
第二个是如何找到列表中共有的东西,像这样:
> cpfx ["abc","ab","abcd"]
"ab"
> cpfx ["abc","abcef","a123"]
"a"
> cpfx ["xabc","xabcef","axbc"]
""
第三个是用input建立这样的图形:
> street [(3,2,'x'),(2,6,'y'),(5,4,'z')]
yy
yy
yyzzzzz
yyzzzzz
xxxyyzzzzz
xxxyyzzzzz
最后一个是输入指令进行相应的几种操作:
> editstr [("rep"," ","_")] "just a test" 这是替换
"just_a_test"
> editstr [("xlt","aeiou","AEIOU")] "just a test" 这个是将相应位置的替换,就是把aeiou替换成AEIOU
"jUst A tEst" aeiou和AEIOU都是由用户输入的
> editstr [("len","","")] "testing" 这个是求长度
"7"
> editstr [("rev","","")] "testing" 这个是反向
"gnitset"
> editstr [("x","3","")] "xy" 这个是重复
"xyxyxy"
小弟有几个Haskell问题想问大神第一个是如何将一个列表拆开就像这样:> :type splits splits ::[a] -> [([a],[a])]> splits [1..4] [([1],[2,3,4]),([1,2],[3,4]),([1,2,3],[4])]> splits "xyz" [("x","yz"),("xy","z")]> splits [True,Fa
第一道用了一个比较笨的办法,而且也没有管列表长度小于2的情况
```haskell
splits xs = sp ((length xs)-1) xs
sp 1 xs = [splitAt 1 xs]
sp n xs = (sp (n-1) xs) ++ [splitAt n xs]
```
第二道题copy自[stackoverflow](http://stackoverflow.com/a/21722065/2214113)
```haskell
commonPrefix :: (Eq e) => [e] -> [e] -> [e]
commonPrefix _ [] = []
commonPrefix [] _ = []
commonPrefix (x:xs) (y:ys)
| x == y = x : commonPrefix xs ys
| otherwise = []
cpfx :: (Eq a) => [[a]] -> [a]
cpfx = foldl1 commonPrefix
```
该睡了,后面两个改天有时间再说,我才不告诉你我不会.