Haskell,如何使用显示函数

标签 haskell

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/

相关文章:

algorithm - 如何在 Haskell 中实现 ThiSTLEthwaite 算法?

haskell - 简单 Haskell Monad - 随机数

windows - Windows 上的 GHC + wxHaskell

haskell - 我应该让我的 Haskell 模块默认安全吗?

haskell - 使用 runReaderT 消除 MonadReader 约束

list - Haskell:如何在(zip [0..])中进行折叠/构建融合?

haskell - Haskell 中的自定义 concat (++) 运算符

haskell - 创建数据类型时派生意味着什么?

haskell - 如何返回从列表前面删除指定数量元素的列表

pdf - 在 Haskell 中将 .rtf 转换为 .pdf