我正在學習使用Haskell的函數式編程入門課程。 練習的一部分是爲輸入字符串編寫解析器。Haskell中的[String]模式匹配
但是我無法解決以下錯誤,或得到實際發生的事情。
Parser.hs:29:71:
Couldn't match expected type `String' with actual type `Char'
In the first argument of `readPoint', namely `start'
In the expression: readPoint start
In the expression:
(readLines track, readPoint start, readLine finish)
錯誤從這一行來源:
readTrack str = parseTrack (lines str) where
parseTrack (start : finish : track) = (readLines track, readPoint start, readLine finish)
我希望發生的是,輸入字符串得到了拆分成線,其中獲得傳遞給parseTrack的列表。 然後,parseTrack將使用模式匹配來從列表和其他名稱中命名前兩個字符串(行)。
但是我相信發生的事情是finish是列表中的頂部元素,並且start會從該字符串中分配頂部字符。
我真的很想知道如何解決這個問題以及實際發生的事情。
非常感謝!
Parser.hs
module Parser where
import Types
readFloat :: String -> Float
readFloat str = case reads str of
[] -> error "not a floating point number"
(p,_):_ -> p
readInt :: String -> Int
readInt str = case reads str of
[] -> error "not an integer"
(p,_):_ -> p
readPoint :: String -> Point
readPoint str = parsePoint (words str) where
parsePoint (x : y : _) = (readInt x, readInt y)
readLine :: String -> Line
readLine str = parseLine (words str) where
parseLine (x1 : y1 : x2 : y2 : _) = ((readInt x1, readInt y1), (readInt x2, readInt y2))
readLines :: String -> [Line]
readLines str = parseLines (lines str) where
parseLines (line : rest) = readLine line : parseLines rest
readTrack :: String -> Track
readTrack str = parseTrack (lines str) where
parseTrack (start : finish : track) = (readLines track, readPoint start, readLine finish)
Types.hs
module Types where
type Vector2D = (Int, Int)
type Point = Vector2D
type Line = (Point, Point)
type Velocity = Vector2D
type CarState = (Position, Velocity)
type Position = Vector2D
type Trace = [Position]
type Track = ([Line], Point, Line)
Wonderfull答案,解決了這個問題,並提高了我對如何評估類型的理解。 +1爲您先生! –