simple function that shifts specific element of a list

后端 未结 2 1967
傲寒
傲寒 2021-01-16 18:06

I am new to Haskell and I am trying to figure out how to make a function:

    shift:: Eq a => a -> [a] -> Int -> [a]
    shift x (h:t) z
<         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-16 18:33

    For you are new to Haskell, it's better to break the problem into simpler subproblems. One trick to solve your problem is:

    thinking of "insert" instead of "shift". Pseudo code:
    - remove x from the list
    - insert x back to the list at the proper position based on given n
    

    You already implement delete, lets take advantage of it. Enjoy simple code:

    -- assume x is in the list, otherwise your problem would not make sense
    shift :: Eq a => a->[a]->Int->[a]
    shift x lst n = if n == 0 then delete x lst 
                    else insert x (n + (position x lst)) (delete x lst)
    

    Sub-problems are:

    1. Delete x from the list: you did that
      delete :: Eq a => a->[a]->[a]
      delete x []          = []
      delete x (head:tail) = if x == head then tail else head : delete x tail
    
    2. find the position of x in the list
      -- assume x in the list
      position :: Eq a => a->[a]->Int
      position x (head:tail) = if x == head then 1 else 1 + position x tail
    
    3. -- insert x into the list at nth position
      insert :: a->Int->[a]->[a]
      insert x n (head:tail) = if n <= 1 then x : (head:tail) 
                               else head : (insert x (n-1) tail)
      insert x n lst         = if n >= length lst then lst ++ [x] 
                               else insert x n lst
    

    Your precondition is that x is in the list, otherwise it does not make sense. If you want to include the case x is not in the list, twist the code.

    Have fun.

提交回复
热议问题