1

I don't know what is wrong with the code. I have just started coding in Haskell so sorry for the trouble.

tobase :: Int -> Int -> [Int]

tobase b x = tobase b (x `quot` b) : [x `mod` b]
tobase b x | x `mod` b == x = [x]
  Couldn't match expected type ‘[Int]’ with actual type ‘Int’
  In the expression: x `mod` b
  In the second argument of ‘(:)’, namely ‘[x `mod` b]’
  In the expression: tobase b (x `quot` b) : [x `mod` b]
4
  • 4
    The second clause will never fire, since the first pattern will always match. Commented Oct 16, 2019 at 21:47
  • 2
    The main poblem is that tobase b (x `quot` b) will generate a list, not an Int itself, hence the type error. Commented Oct 16, 2019 at 21:48
  • 1
    Thank you. I concatenated the list and now it works. Commented Oct 16, 2019 at 21:57
  • 2
    @shubhushanshambhu Can you add your solution as an answer? Then you can accept it so this question appears as ‘solved’. Commented Oct 16, 2019 at 22:54

1 Answer 1

1

As Willem has already indicated, the reason for the error is that you are trying to combine values of the wrong type via the "cons" operator (:). This operator's signature is (:) :: a -> [a] -> [a] , not (:) :: [a] -> [a] -> [a], which is what your call is attempting.

Your tobase function returns type [Int], and it's the first argument passed to the : operator. Since the type variable a in (:) :: a -> [a] -> [a] has this [Int] type in your invocation, the compiler expects the second argument to be [[Int]]. However you are passing in [x `mod` b] which is of type [Int]. Instead of using : you can use ++ to combine the two lists.

As also noted, the pattern matching order in your function definition should be reversed because the second case tobase b x | x `mod` b == x = [x] will never be reached. See http://learnyouahaskell.com/syntax-in-functions

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.