import Data.List (sort,nub,(\\),transpose,genericLength)
import Data.String (lines,unlines)


type Row a    = [a]
type Matrix a = [Row a]
type Digit    = Char

digits :: [Digit]
digits = ['1'..'9']

blank :: Digit -> Bool
blank d = d == ' '

-- 1.
group :: [a] -> [[a]]
group = groupBy 3

groupBy :: Int -> [a] -> [[a]]
groupBy _ [] = [] 
groupBy n xs = let (ys, zs) = splitAt n xs
               in  ys : groupBy n zs

-- 2.
intersperse :: a -> [a] -> [a]
intersperse x y = x : [ x | ys <- y, x <- [ys, x]]

-- 3.
showRow :: String -> String
showRow xs = intersperse "|" (groupBy 3 xs)

Komunikat o błędzie poniżej

Tutorial9.hs:35:14: error:
    • Couldn't match type ‘[Char]’ with ‘Char’
      Expected type: String
        Actual type: [[Char]]
    • In the expression: intersperse "|" (groupBy 3 xs)
      In an equation for ‘showRow’:
          showRow xs = intersperse "|" (groupBy 3 xs)
   |
35 | showRow xs = intersperse "|" (groupBy 3 xs)
   |   

       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

Funkcja group działa dobrze, ale nie wydaje się działać, gdy nazywam to showRow. Dlaczego?

0
CamelBak 23 listopad 2020, 00:33

1 odpowiedź

Najlepsza odpowiedź

intersperse :: a -> [a] -> [a] ** zwróci [String] nie String, ponieważ groupBy 3 xs powróci [String] i separator jest String. Możesz skorzystać z { {X6}} , aby połączyć struny razem:

showRow :: String -> String
showRow xs = concat (intersperse "|" (groupBy 3 xs))

Albo możesz skorzystać z intercalate :: [a] -> [[a]] -> [a] , co już robi:

import Data.List(intercalate)

showRow :: String -> String
showRow xs = intercalate "|" (groupBy 3 xs)
5
Willem Van Onsem 22 listopad 2020, 21:37