Eli*_*ard 1 haskell functional-programming list idiomatic
我对Haskell和函数式编程很新,所以我真的不知道如何使这个代码成为惯用语:
type Coord = Double
data Point = Point Coord Coord Coord deriving Show
type Polyline = [Point]
-- Add a point to a polyline
addPoint :: Polyline -> Point -> Polyline
addPoint line p = p:line
line :: Polyline
line = []
constructLine :: Polyline -> Polyline
constructLine line =
let
p1 = Point 2 4 87
p2 = Point 3 7 2
p3 = Point 23 4 8
in addPoint (addPoint (addPoint line p1) p2) p3
main :: IO()
main = do
putStrLn ( show (constructLine line))
Run Code Online (Sandbox Code Playgroud)
我的问题在于constructLine功能.如果我想添加很多点,嵌套addPoint函数将成为一个问题.我怎么能这个因素呢?你还看到其他可以改进的东西吗?
对addPoints的多次调用可以用折叠代替.正如评论中所建议的,反转你的addPoint函数会让事情变得更容易:
addPoint' :: Point -> Polyline -> Polyline
addPoint' p line = p:line
Run Code Online (Sandbox Code Playgroud)
那么你的constructLine函数可以构建一个临时的点列表来添加使用折叠:
constructLine :: Polyline -> Polyline
constructLine line =
let
p1 = Point 2 4 87
p2 = Point 3 7 2
p3 = Point 23 4 8
in foldr addPoint' line [p3,p2,p1]
Run Code Online (Sandbox Code Playgroud)
这不会破坏封装(你可以用Point列表替换你的Polyline的实现)并按照它们最终的顺序使用新的点(p2前面的p3等)
| 归档时间: |
|
| 查看次数: |
129 次 |
| 最近记录: |