[Haskell-beginners] Just clarifying the "pred" and "succ"
functions in Haskell
Brandon S. Allbery KF8NH
allbery at ece.cmu.edu
Sat Feb 6 00:54:37 EST 2010
On Feb 6, 2010, at 00:27 , Andy Elvey wrote:
> However, is my understanding correct that this can be extended to
> lists (arrays in C) so that (for example) for a list ["foo", "bar",
> "baz"] , "pred "bar" " would give you "foo" , and "succ "bar" "
> would give you "baz"?
No. Leaving aside that you don't manipulate lists that way in
Haskell, "bar" is a random value of type String (which is [Char]), not
a member of an enumeration. For comparison:
> data MyType = Foo | Bar | Baz deriving Enum;
> -- pred Bar = Foo, succ Bar = Baz
Some languages (e.g. Perl) do give an enumerable value to Strings, but
`succ "Bar"' would be something like "Baq". (This could be done in
Haskell, with some pain; it starts with `instance (Enum a, Bounded a)
=> Enum [a] where...'.) You can't go from a string like "Bar" to
whatever lists might contain that string (and what if multiple lists
contained it?), so there's no way to get an interpretation like that;
you would need an enumerator which had access both to the list and the
member in question, whereas Enum has access only to the type. (There
exist dependent type systems where you could encode that information
into a defined (sub)type, but Haskell doesn't support it directly.)
What you *can* do is that, because the types of list and array indexes
are members of Enum, you can for example use Data.List.index to
determine the index (if any!) of that item in your list, then take
prev or succ of that. Beware of running off the end of the list,
though. (It's also more complicated for arrays because array indexes
are themselves defined by a typeclass `Ix'.)
--
brandon s. allbery [solaris,freebsd,perl,pugs,haskell] allbery at kf8nh.com
system administrator [openafs,heimdal,too many hats] allbery at ece.cmu.edu
electrical and computer engineering, carnegie mellon university KF8NH
-------------- next part --------------
A non-text attachment was scrubbed...
Name: PGP.sig
Type: application/pgp-signature
Size: 195 bytes
Desc: This is a digitally signed message part
Url : http://www.haskell.org/pipermail/beginners/attachments/20100206/e33481eb/PGP.bin
More information about the Beginners
mailing list