Haskell insert an element on nth position -
hi started learn haskell can't figure out 1 topic.
let's have list: [1,2,3] , i'm trying write function insert element on nth position. clues how do this?
you can build insertat function this:
insertat :: -> int -> [a] -> [a] insertat newelement 0 = newelement:as insertat newelement (a:as) = : insertat newelement (i - 1) one strategy such problems write code edge cases , use recursion until edge case found.
the mentioned lens package simplifies handling data structures in sense code may become shorter , nicer write, @ expense of additional library learn.
both examples highlight there several ways achieve solution problem. recommend having @ data.list module gain further insight typical list operations. source drop function start you. provided splitat function fitting building block problem.
as shersh mentions correctly above implementation of insertat flawed: doesn't check negative positions , in case of 1 given continues recursing. can particularly bad in case of infinite list.
we can improve implementation using guards:
insertat :: -> int -> [a] -> [a] insertat newelement _ [] = [newelement] insertat newelement (a:as) | <= 0 = newelement:a:as | otherwise = : insertat newelement (i - 1) this implementation tries right thing inserting newelement when in doubt. possible write version of insertat instead throws errors our face:
import data.monoid ((<>)) import qualified data.list list insertat :: -> int -> [a] -> [a] insertat newelement | null && != 0 = error "cannot insert empty list other position 0." | null && == 0 = [newelement] | >= 0 = let (prefix, suffix) = list.splitat in prefix <> [i] <> suffix this version makes use of list.splitat brevity.
Comments
Post a Comment