type Start = String
type Destination = String
type Distance = Float -- km
type AverageSpeed = Float -- m/s
type FirstClass = Bool
data Trip = Trip Start [TravelOption]
data TravelOption = Plane AverageSpeed Destination Distance FirstClass | Bus AverageSpeed Destination Distance | Train AverageSpeed Destination Distance FirstClass
class VacationTrip a
where
instance Show TravelOption
where
show (Plane speed dest distance firstClass) = " by plane to " ++ dest
show (Bus speed dest distance) = " by bus to " ++ dest
show (Train speed dest distance firstClass) = "by train to " ++ dest
instance Show Trip
where
show (Trip start travelOptions) = "[" ++ start ++ "]" ++ formatList (map show travelOptions)
where
formatList :: [String] -> String
formatList [] = ""
formatList [x] = "[" ++ x ++ "]"
formatList (x:xs) = "(" ++ x ++ ") " ++ formatList xs
我应该如何更改我的 show 或 formatList 函数,以便获得我需要的输出? 我需要这样的输出;
[出发]乘飞机到(下一个城市)乘火车到(下一个城市乘火车到[最后一个城市]。
城市应位于括号内(最后一个必须位于方括号内)
我用我的代码得到的是这样的; [阿姆斯特丹](乘飞机到柏林)(乘火车到巴黎)[乘火车到科隆]
我希望我能解释我的问题...
最佳答案
您可以首先创建 show
函数的参数化变体,用于确定如何设置城市格式:
showWith :: (String -> String) -> TravelOption -> String
showWith <b>f</b> = go
where
go (Plane speed dest distance firstClass) = " by plane to " ++ <b>f dest</b>
go (Bus speed dest distance) = " by bus to " ++ <b>f dest</b>
go (Train speed dest distance firstClass) = "by train to " ++ <b>f dest</b>
instance Show TravelOption where
show = showWith <b>id</b>
然后我们可以用它来格式化序列:
squareBrackets :: String -> String
squareBrackets x = '[' : x ++ "]"
parenthesis :: String -> String
parenthesis x = '(' : x ++ ")"
instance Show Trip where
show (Trip start travelOptions) = squareBrackets start ++ formatList travelOptions
where
formatList [] = ""
formatList [x] = ' ' : <b>showWith squareBrackets x</b>
formatList (x : xs) = ' ' : <b>showWith parenthesis x</b> ++ formatList xs
关于Haskell,如何使用显示函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76623309/