haskell - How to change this function to work with any type, not just Int -


i have written following function @ 1 time in past, replace instance of integer x in list, integer y. here's code:

substitute::int->int->[int]->[int] substitute x y []           =[] substitute x y (z:zs)     |(z==x)                 =y:substitute x y (zs)     |otherwise              =z:substitute x y (zs) 

here's sample call:

main = print $ substitute 2 3 [2, 2, 2] 

i want make code work input type. tried converting parameter types generic "a", spits out error haskell thinks sort of customary higher-order function. how can make work:

substitute::a->a->[a]->[a] substitute x y []           =[] substitute x y (z:zs)     |(z==x)                 =y:substitute x y (zs)     |otherwise              =z:substitute x y (zs)   main = print $ substitute 2 'a' [2, 2, 2] 

one way find out remove type signature code , find out using ghci:

λ> :t substitute substitute :: eq => -> -> [a] -> [a] 

haskell has type inference, automatically give polymorphic type you.

substitute :: eq => -> -> [a] -> [a] substitute x y []           =[] substitute x y (z:zs)     |(z==x)                 =y:substitute x y (zs)     |otherwise              =z:substitute x y (zs) 

update: saw updated question. haskell doesn't have heterogeneous list default, want cannot done. can use existential data type want. read this section understand more it.

{-# language existentialquantification #-}  data showbox = forall s. show s => sb s  instance show showbox   show (sb s) = show s    substitute :: showbox -> showbox -> [showbox] -> [showbox] substitute x y []           =[] substitute (sb x) (sb y) ((sb z):zs)     |(show z ==  show x) = (sb y):substitute (sb x) (sb y) (zs)     |otherwise              = (sb z):substitute (sb x) (sb y) (zs)  λ> substitute (sb 'a') (sb 3) [sb 1, sb 'a', sb 3] [1,3,3] 

note above program anti pattern. don't unless have right reasons.


Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -