1

I'm having trouble with this function, i need it to give the binary form of a number as a list of 4 elemnts ( just from 0 to 15) so for example for the input 0 it should give me [0,0,0,0], 3 : [0,0,1,1] , 15 [1,1,1,1] so that's what i did

bin 0 x = []
bin n x = (mod x 2) : (bin (n-1) (div x 2))

It gives the result in backwards and this :

bin 0 x = []
bin n x =  (bin (n-1) (div x 2)) ++ (mod x 2)

don't work, when compiling it doesn't show an error, but when i enter for example bin 4 1 it shows :

"No instance fo ( Integral [t0]) arising from a use of 'it'
In a stmt of an interactive GHCi command : print it "

I can't figure out what to do, any help will be appreciated

2
  • 1
    try to add type signatures for your function - that increases the helpfulness of error messages - also think what mod x 2 is and what it should be if you use it with (++) (hint try to use those square brackets) Commented Jan 25, 2016 at 9:50
  • Thank you @epsilonhalbe i realise now that ++ is used between 2 lists Commented Jan 25, 2016 at 10:02

1 Answer 1

4

++ takes two lists and mod x 2 is not a list. You can use

... ++ [mod x 2]

However, be warned that repeatedly adding an element at the end of a list like that is inefficient, leading to quadratic complexity.

It's better to use your first snippet which produces the bits backwards and then using reverse to rearrange the bits in the forward direction at the end. This will provide linear complexity.

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

Comments

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.