[Oz] [Haskell] Function that inserts element to a given position in a list

Below are example code in Oz and Haskell for the function that inserts an element at a given position in a list. The position should be counted from the end of the list.

Mozart Oz Programming Language

declare
fun {Insert A Pos L}
   {FoldR L (fun {$ X Y}
  case Y of nil then nil
  [] S#I then
     if I \= Pos-1 then
        {Append [X] S}#(1+I)
     else
        {Append [A X] S}#(1+I)
     end
  end
      end) ({List.drop [A] Pos}#0)}.1
end

{Browse {Insert 10 0 [a b c d e]}} %shows [a b c d e 10]

Haskell Programming Language

module Main where

insert :: a -> Int -> [a] -> [a]
insert x n [] = []
insert x n xs = f ++ [x] ++ drop (length xs - n) xs
 where f = (take (length xs - n) xs)
-- insert "x" 1 ["a","b","c","d","e"] 


References:
http://www.haskell.org/ghc/docs/6.12.1/html/libraries/base/src/Data-List.html#insert
http://defowl.blogspot.com/2007/04/coding-in-haskell.html

Comments

Popular posts from this blog

[Azure Websites PHP] Cross Domain request results in blank response page after Preflight HTTP OPTIONS

[Magento] Create Contact Form with Dynamic Recipient