Home > front end >  How can I make this mountain Haskell code work?
How can I make this mountain Haskell code work?

Time:03-09

How can I put the 2 list in 1 list, because this code only give me back the fisrt list.

mountain :: Int -> [Int]

mountain 0 = [0]
mountain 1 = [0]
mountain 2 = [0,2,0]
mountain 3 = [0,2,0]
mountain x 
    | x `mod` 2 == 0 = [0,2..x]    [x-2..0]
    | otherwise = [0,2..x-1]    [x-3..0]
    
Examples:
--mountain 0 == [0]
--mountain 6 == [0,2,4,6,4,2,0]
--mountain 7 == [0,2,4,6,4,2,0]
--mountain 10 == [0,2,4,6,8,10,8,6,4,2,0]

CodePudding user response:

[x-2 .. 0] will be empty, since there is no "then" item, it will make steps of one. You can make such list with [x-2, x-4 .. 0]. You can implement the mountain function with:

mountain :: Int -> [Int]
mountain i = [0, 2 .. n]    [n-2, n-4 .. 0]
    where n = 2 * div i 2
  • Related