简体   繁体   中英

Haskell datatype syntax with manipulation

I'm a novice with no functional programming experience in the past (yet, quite a bit of procedural/imperative programming experience). I'm having a bit of trouble with understanding how declaring your own datatype works.

For instance, say I declared a datatype:

data SomeThing = Int [Int]

how would you write a Haskell function which consumes a someData and produces a someData; only the produced data's Int is the sum of all the elements in the consumed data's [Int], and where the consumed value's [Int] has had every element multiplied by 2 in the produced [Int].

This is obviously possible, but I have not found any answers that made sense to me after a web search.

First of all, you have a mistake in your data type declaration. From your question, you want a data type which contains an Int and a list of Int , but you're missing a data constructor 1 . This is a label used when pattern matching, or when constructing new values of your data type.

data SomeThing = SomeThingConstr Int [Int]

It's common to name the constructor the same thing as the data type itself when there's only one, but I've given them separate names here to avoid confusion.

Now it's easy to write your function using pattern matching and this data constructor.

foo :: SomeThing -> SomeThing
foo (SomeThingConstr _ xs) = SomeThingConstr (sum xs) (map (*2) xs)

1 Or rather, you have a data constructor called Int , which is obviously not what you meant.

(Quoting from your post as I suspect it will get edited.)

For instance, say I declared a datatype:

 data SomeThing = Int [Int] 

how would you write a Haskell function which consumes a someData and produces a someData; only the produced data's Int is the sum of all the elements in the consumed data's [Int], and where the consumed value's [Int] has had every element multiplied by 2 in the produced [Int].

I presume you mean the data type to be

data SomeData = SomeData Int [Int]

Then you want

f :: SomeData -> SomeData
f (SomeData _ ys) = SomeData (sum ys) (map (2 *) ys)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM