0

I am beginner level of the Haskell Language and I was trying to implement Insertion Sort function in Haskell in ghci environment.

here's my code.

prelude> let insert x [] = x:[]

insert :: t1 -> [t] -> [t1]

prelude> let insert x (y:ys) = 
if x < y then x:y:ys else y : insert ys


insert :: Ord a => a -> [a] -> [a]

I tried

insert 1 []

the result was [1], It worked well.

and I tried

insert 1 ([2,3]) 

the result was [1,2,3], Still it works well.

(Actually, I don't know why I have to parse on second argument list. but if I try insert 1 [2,3], it doesn't work.)

it worked well until this. but when I tried

insert 4 ([1,2,3]) 

It happened like this.

[1,2,3*** Exception: <interactive>:165:5-61: Non-exhaustive patterns in function 

I don't why it did happen like this.please help me.

Kara
  • 6,115
  • 16
  • 50
  • 57
Princeps
  • 3
  • 3

1 Answers1

2

you are overwriting your first function let insert x [] = x:[] with another one (in your next let insert ... - this happens because you use let ... inside GHCi)

Instead you should create .hs file and load this into GHCi instead.

So fire up your favorite editor and insert this:

module MyInsertSort where

insert :: Ord a => a -> [a] -> [a]
insert x []     = x:[]
insert x (y:ys) = if x < y then x:y:ys else y : insert x ys

save it (I did as MyInsert.hs), start ghci and load it into it:

λ> :l MyInsert.hs
[1 of 1] Compiling MyInsertSort     ( MyInsert.hs, interpreted )
Ok, modules loaded: MyInsertSort.
λ> insert 4 ([1,2,3])
[1,2,3,4]

λ> insert 1 ([2,3])
[1,2,3]

now it should work :D

remarks

you had a small error in your second line insert ys instead of insert x ys

Random Dev
  • 51,810
  • 9
  • 92
  • 119
  • Thanks for your help :) but Is there other way to implement function in ghci directly? – Princeps Apr 26 '15 at 12:26
  • see http://stackoverflow.com/questions/2846050/how-to-define-a-function-in-ghci-across-multiple-lines – hasufell Apr 26 '15 at 12:36
  • @hasufell why not - maybe the OP will like that - I usually don't recommend this because you will learn to hate this quite quickly (when you reentered the thing the 3rd time) and writing a quick file (or even using emacs/vim) is much faster and better to experiment in the long run - after all it will take some time for Princeps to finish his insert-sort – Random Dev Apr 26 '15 at 12:48
  • I agree, I also rather load files via ghci and benefit from the power of my editor (syntax highlighting, hlint support etc.). – hasufell Apr 26 '15 at 13:20