user2226112
user2226112

Reputation:

Can't get rid of this type error

I'm trying to solve this problem.

This is my code:

import Data.List (nub)

main = interact $ unwords . map show . solve . map words . lines

solve :: [[String]] -> [Int]
solve (_:r:_:a) = map (rank . read) a
    where records = nub $ map read r :: [Int]
          rank n = (length $ takeWhile (> n) records) + 1

The compiler throws this error:

    * Couldn't match type `[Char]' with `Char'
      Expected type: [String]
        Actual type: [[String]]
    * In the second argument of `map', namely `a'
      In the expression: map (rank . read) a
      In an equation for `solve':
          solve (_ : r : _ : a)
            = map (rank . read) a
            where
                records = nub $ map read r :: [Int]
                rank n = (length $ takeWhile (> n) records) + 1
  |
6 | solve (_:r:_:a) = map (rank . read) a
  |

I don't understand what the issue is. When I piece it together line by line in GHCi, it works:

GHCi> import Data.List (nub)
GHCi> records = nub $ map read ["100", "100", "50", "40", "40", "20", "10"] :: [Int]
GHCi> rank n = (length $ takeWhile (> n) records) + 1
GHCi> a = ["5", "25", "50", "120"]
GHCi> map (rank . read) a
[6,4,2,1]

Upvotes: 2

Views: 58

Answers (1)

Dannyu NDos
Dannyu NDos

Reputation: 2498

You made a wrong pattern matching. As solve must accept a list of size of exactly 4, the pattern matching must be like this:

solve [_,r,_,a] = ...

Which can be de-sugared to:

solve (_:r:_:a:[]) = ...

Or even further de-sugared:

solve (_:(r:(_:(a:[])))) = ...

Remember, : takes an element on left and a list on right!

Upvotes: 1

Related Questions