Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
237 views
in Technique[技术] by (71.8m points)

haskell - Having trouble with groupBy function

I am having trouble with the groupBy function I want to split at the number. Helpful if someone can point out where I am going wrong

Input "aba3dac4d"

Desired Output ["aba", "3dac", "4d"]

But I get the output when I execute code

groupBy groupBy0' "aba3dac4d"

["aba", "3dac4d"] Here is the code

import Data.List

groupBy0'::Char->Char->Bool
groupBy0' x y
  | x `elem` ['a'..'z'] && y `elem` ['0'..'9'] = False
  | x `elem` ['0'..'9'] && y `elem` ['a'..'z'] = True
  | x `elem` ['a'..'z'] && y `elem` ['a'..'z'] = True
  | x `elem` ['0'..'9'] && y `elem` ['0'..'9'] = True
  | otherwise = False
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the docs:

The "By" operations

By convention, overloaded functions have a non-overloaded counterpart whose name is suffixed with By.

It is often convenient to use these functions together with on, for instance sortBy (compare `on` fst).

User-supplied equality (replacing an Eq context)

The predicate is assumed to define an equivalence.

So, groupBy pred expects that pred is an equivalence relation, but yours is not, breaking the contract, so the result can not be relied upon. In particular, groupBy groupBy0' "aba3dac4d" is likely to perform these tests:

  • groupBy0' 'a' 'b' is true, 'b' in same group
  • groupBy0' 'a' 'a' is true, 'a' in same group
  • groupBy0' 'a' '3' is false, '3' in other group
  • groupBy0' '3' 'd' is true, 'd' in same group
  • groupBy0' '3' 'a' is true, 'a' in same group
  • groupBy0' '3' 'c' is true, 'c' in same group
  • groupBy0' '3' '4' is true, '4' in same group
  • groupBy0' '3' 'd' is true, 'd' in same group

As you can see, the above implementation of groupBy, we always compare with the first element in the group, not with the last one as you expect. Since pred is assumed to be an equivalence, it does not matter which element in the group we compare with. If we break this assumption, it matters.

You can't use groupBy to perform your particular function.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...