Saturday, 30 April 2016

Haskell: As-patterns (@)


As pattern is represented like variable@value, it means it binds the value to the variable.

For example, following program find all the suffixes of a string using As pattern.

listUtil.hs
getSuffixes :: [Char] -> [[Char]]
getSuffixes [] = []
getSuffixes str@(x:xs) = str : getSuffixes xs

*Main> :load listUtil.hs
[1 of 1] Compiling Main             ( listUtil.hs, interpreted )
Ok, modules loaded: Main.
*Main> 
*Main> getSuffixes ""
[]
*Main> getSuffixes "Hello"
["Hello","ello","llo","lo","o"]
*Main> 
 
'str@(x:xs)' binds the variable str to the value that matches the right side of the @ symbol.


Previous                                                 Next                                                 Home

No comments:

Post a Comment