0

I'm trying to create an insertion sort method that allows me to do an insertion sort based on a function of an item, eg function applied to 1 could be greater than function applied to 2 or vice versa depending on the function.

I have this so far to work out if I can insert an element into a part of a list.

insertBy :: Ord b => (a -> b) -> a -> [a] -> [a] 
insertBy f a [] = [a]
insertBy f a (x:xs) = if ( (f a)< (f x )) then a:x:xs else insertBy f a xs

However, I'm getting a parse error on the second line. Sorry if it's really obvious but I can't see it.

Once I have that part I will call an insertion sort function that uses that to sort a list but first I need help with this :(

edit: exact error "Parse error in Pattern insertBy"

3
  • In this kind of question, it would be good if you would give us the error message you're seeing. Commented Nov 2, 2013 at 4:11
  • When I insert exactly this text into a module on its own, ghc compiles it fine, and does what it's supposed to, including the bug mentioned below. Same appears to be true for hugs. Commented Nov 2, 2013 at 4:28
  • There is nothing wrong with the formatting of the code you have on here. I would guess you have made a typo or some other error in your local copy of the code. Commented Nov 2, 2013 at 13:11

1 Answer 1

1

I think you want the final expression to be

x : insertBy f a xs

Otherwise you're discarding the first element of the list in that case.

Sign up to request clarification or add additional context in comments.

2 Comments

yeah you're right but I still get the same error. There is something wrong with line 2
insertBy is already defined in the haskell library. I fixed it by changing any reference to insertBy to insertBy1. Thanks for that bug also!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.