domi
domi

Reputation: 133

Beginner: Converting Types in Haskell

First post here, please go easy on me. Found several threads with similar issues, none of those applied directly or if one did, the execution was far enough over my head.

If i have code p=['1','2','3','4'] that stores digits as characters in p, how do i create a list q that can equal [1,2,3,4]? I've been trying all sorts of things, mostly arriving at my q being out of scope or any function i try to convert Char -> Int lacking accompanying binding. I seem to find indication everywhere that there is such a thing as digitToInt, where digitToInt '1' should yield an output of 1 but i apparently lack bindings, even with the exact input from this page: http://zvon.org/other/haskell/Outputchar/digitToInt_f.html

At this point reading more things i am just becoming more confused. Please help with either a viable solution that might show me where i'm messing up or with an explanation why this digitToInt :: Char -> Int seems to not work for me in the slightest.

Thank you.

Upvotes: 4

Views: 118

Answers (2)

Shoe
Shoe

Reputation: 76240

Without importing anything you can also use a very simply trick, and push ((:[])) the character in an empty list (making a singleton list) before reading the value:

map (read . (:[])) "1234"

This will need the context of the type of the list to be deducible, but it will work for any type you want without modifications. Otherwise you'll need to specify the type yourself:

(map (read . (:[])) "1234") :: [Int]
-- [1,2,3,4]
(map (read . (:[])) "1234") :: [Double]
-- [1.0,2.0,3.0,4.0]

Upvotes: 0

Cirdec
Cirdec

Reputation: 24156

digitToInt is something that already exists. It used to live in the Char module but now it lives in Data.Char, so we have to import Data.Char to use it.

Prelude> import Data.Char
Prelude Data.Char> digitToInt '1'
1

You can use digitToInt on every element of a list with map digitToInt. map :: (a->b) -> [a] -> [b] applies a function (a->b) to each element of a list of as, [a] to get a list of bs, [b].

Prelude Data.Char> map digitToInt ['1', '2', '3', '4']
[1,2,3,4]

Lacks an accompanying binding

You don't need to define digitToInt or other imports by writing it's type signature digitToInt :: Char -> Int. A signature written without a binding like that

alwaysSeven :: Char -> Int

will give the following error.

The type signature for `alwaysSeven' lacks an accompanying binding

You only provide a type signature when it comes right before a declaration.

alwaysSeven :: Char -> Int
alwaysSeven x = 7

Upvotes: 9

Related Questions