Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...