该函数应用三个参数

Pla*_*Pro 1 haskell

我需要创建一个元组列表,每个元组代表一个带(x,y,height,width)的矩形.
宽度不变,我需要加倍高度值.

必要的输出:

> genRects 3 (0,0)
 [(0.0,0.0,5.5,5.5),(5.5,0.0,5.5,5.5),(11.0,0.0,5.5,5.5),(16.5,0.0,5.5,5.5)]  
Run Code Online (Sandbox Code Playgroud)

我目前的代码:

genRects :: Int -> (Int,Int) -> [(Float,Float,Float,Float)]
genRects 0 _ = []
genRects n (x,y) = let height=5.5; width=5.5 in [(fromIntegral x, fromIntegral y, height, width)] genRects (n-1) (x+height, y)  
Run Code Online (Sandbox Code Playgroud)

得到错误:

Couldn't match expected type `(Int->(Int, Int)-> [(Float, Float, Float, Float)])
                                  -> Int -> (Int, Int) -> [(Float, Float, Float, Float)]'
                with actual type `[(Integer, Integer, Double, Double)]'
    The function `[(fromIntegral x, fromIntegral y, height, width)]'
    is applied to three arguments,
    but its type `[(Integer, Integer, Double, Double)]' has none
    In the expression:
      [(fromIntegral x, fromIntegral y, altura, comp)]
        genRects (n - 1) (x + x, y)
    In the expression:
      let
        height= 5.5
        width = 5.5
      in
        [(fromIntegral x, fromIntegral y, height, width)]
          genRects (n - 1) (x + x, y)
Failed, modules loaded: none.  
Run Code Online (Sandbox Code Playgroud)

另外为什么它会加倍而不是Float?

JHo*_*ern 6

看一下

[(fromIntegral x, fromIntegral y, height, width)] genRects (n-1) (x+height, y)
Run Code Online (Sandbox Code Playgroud)

这没有意义.你要做的是创建一个矩形,并将其纳入所有其他矩形,所以你应该使用像

(fromIntegral x, fromIntegral y, height, width): genRects (n-1) (x+height, y)
Run Code Online (Sandbox Code Playgroud)

但是,在进行此更改后,您将看到

Couldn't match expected type `Int' with actual type `Float'
In the second argument of `(+)', namely `height'
In the expression: x + height
In the second argument of `genRects', namely `(x + height, y)'
Run Code Online (Sandbox Code Playgroud)

这是有道理的,你试图Float在x值上添加一个(5.5),你说的是一个Int.最简单的解决方案是使用Floats表示x,y,而不是Ints.所以你可以改变你的代码,

genRects :: Int -> (Float,Float) -> [(Float,Float,Float,Float)]
genRects 0 _ = []
genRects n (x,y) = let height=5.5; width=5.5 in (x, y, height, width): genRects (n-1) (x+height, y) 
Run Code Online (Sandbox Code Playgroud)

并获得理想的结果.