首页 > 解决方案 > 字符串加倍?

问题描述

所以对于我的任务,我必须创建几个函数(Haskell 的新函数)。我可以很容易地做到以下几点

data Shape
    = Circle Double -- radius
    | Square Double -- length
    | Rectangle Double Double --length and width
    deriving (Show)

showShape :: Shape -> String
showShape (Circle r) = "circle of radius " ++ show r
showShape (Square l) = "square of length " ++ show l
showShape (Rectangle l w) = "rectangle of length " ++ show l ++ " and width " ++ show w

area :: Shape -> String
area (Circle r) = 
    "Circle of radius " ++ show r ++ " has an area of " ++ show (pi * r * r)

除了我的任务特别希望我使用

area :: Shape -> Double

我该怎么做?

标签: haskell

解决方案


如果你这样做:

data Shape
    = Circle Double -- radius
    | Square Double -- length
    | Rectangle Double Double --length and width
    deriving (Show)

showShape :: Shape -> String
showShape (Circle r) = "circle of radius " ++ show r
showShape (Square l) = "square of length " ++ show l
showShape (Rectangle l w) = "rectangle of length " ++ show l ++ " and width " ++ show w

area :: Shape -> Double
area (Circle r) = (pi * r * r)

这个对我有用。

我认为你的问题是你试图在同一个函数中做两件事:

  1. 计算面积
  2. 返回该区域的漂亮字符串信息

你的函数,area :: Shape -> Double应该只计算面积。


推荐阅读