algorithm - Interspace program in Haskell -


insert :: eq(a) => -> -> [a] -> [a] insert m n [] = [] insert m n (x:xs) | m==x = n : x : insert m n xs                    | otherwise = x : insert m n xs 

the insert function above working function inserts value n list before instances of value m.

i need writing interspace function inserts value n between values m , q in list. have far:

 interspace :: eq(a) => -> -> a->[a] -> [a]   interspace m n q[] = []   interspace m n q (x:xs)| m==x && q==(head xs)  = n: x : insert m n (headxs)++interspace m n q (xs)                           | otherwise = x : interspace m n q xs 

since adding values front of list, insert function unnecessary. (:) suffice instead. in insert, pass recursively on list. since want check if 2 values match @ time , call function recursively on different lists based on whether or not find match, it's idea pattern match (x1:x2:xs) rather (x:xs).

if m matches x1 , q matches x2, place onto head of list , call interspace recursively on rest of list. if not mach, call interspace on (x2:xs).

 interspace :: eq => -> -> a-> [a] -> [a]  interspace m n q []         = []  interspace m n q [x]        = [x]  interspace m n q (x1:x2:xs) | m == x1 && q == x2 = m : n : q : interspace m n q xs                              | otherwise          = x1 : interspace m n q (x2:xs) 

example usage:

ghci>> interspace 1 2 1 [1,1,2,1,1] [1,2,1,2,1,2,1] ghci>> interspace 1 2 1 [1,1,3] [1,2,1,3] ghci>> interspace 1 2 1 [1,2,4,2] [1,2,4,2] ghci>> interspace 1 2 1 [1] [1] ghci>> interspace 1 2 1 [] [] 

Comments

Popular posts from this blog

java - SSE Emitter : Manage timeouts and complete() -

jquery - uncaught exception: DataTables Editor - remote hosting of code not allowed -

java - How to resolve error - package com.squareup.okhttp3 doesn't exist? -