Sum of Squares using Haskell

前端 未结 3 1871
梦毁少年i
梦毁少年i 2020-12-06 23:31

I\'m trying to carry out the following computation: sum of the squares of integers in the range x:y where (x <= y).

I\'m not sure how to put a constraint to ensur

3条回答
  •  死守一世寂寞
    2020-12-06 23:58

    In GHCI do these steps to see what's going on:

    Prelude> let sq x = x^2
    Prelude> let list = [1..5]
    Prelude> list
    [1,2,3,4,5]
    Prelude> let listOfSq = map sq list
    Prelude> listOfSq
    [1,4,9,16,25]
    
    Prelude> sum listOfSq
    55
    

    The shorthand would be exactly what Jubobs suggested:

    sum $ map (^2) [1..5]
    

    EDIT: To error out when Y is greater than X you can do something like this

    sumOfSquares :: Integer -> Integer -> Integer
    sumOfSquares x y  | y <= x = error "Y must be greater than X"
                      | otherwise = sum $ map (^2) [x..y]
    

提交回复
热议问题