gpt4 book ai didi

haskell - 这个haskell样本可以更短吗?

转载 作者:行者123 更新时间:2023-12-04 16:35:18 25 4
gpt4 key购买 nike

这是我从 YAHT 锻炼的解决方案:

Exercise 4.6 Write a datatype Tuple which can hold one, two, three or four elements, depending on the constructor (that is, there should be four constructors, one for each number of arguments). Also provide functions tuple1 through tuple4 which take a tuple and return Just the value in that position, or Nothing if the number is in valid (i.e., you ask for the tuple4 on a tuple holding only two elements).



当我写第一行时,我对与 C# 相比的简单性感到兴奋

数据元组 a b c d = Tuple1 a |元组2 a b |元组3 a b c |元组4 a b c d

-- 类 Tuplex {
-- Tuplex(a p1){ _p1 = p1; }
-- Tuplex(a p1, b p2){ _p1 = p1; _p2 = p2; }
-- Tuplex(a p1, b p2, c p3){ _p1 = p1; _p2 = p2; _p3 = p3; }
-- Tuplex(a p1, b p2, c p3, d p4){ _p1 = p1; _p2 = p2; _p3 = p3; _p4 = p4; }
-- 公共(public) Nullable _p1;
-- 公共(public) Nullable _p2;
-- 公共(public) Nullable _p3;
-- 公共(public) Nullable _p4;
-- }

在 C# 中,我可以毫无问题地访问任何字段,但在这里我应该编写一个“访问器函数”,对吧?这里的代码量让我很难过。

我可以在这里有更短的代码吗?

元组 1 ∷ 元组 a b c d → 可能 a
tuple2 ∷ 元组 a b c d → 也许 b
tuple3 ∷ 元组 a b c d → 可能 c
tuple4 ∷ 元组 a b c d → 可能 d
tuple1 (Tuple1 a) = 只是一个
tuple1 (Tuple2 a b) = 只是一个
tuple1 (Tuple3 a b c) = 只是一个
tuple1 (Tuple4 a b c d) = 只是一个
tuple2 (Tuple1 a) = 无
tuple2 (Tuple2 a b) = 只是 b
tuple2 (Tuple3 a b c) = Just b
tuple2 (Tuple4 a b c d) = 只是 b
tuple3 (Tuple1 a) = 没有
tuple3 (Tuple2 a b) = 没有
tuple3 (Tuple3 a b c) = 只是 c
tuple3 (Tuple4 a b c d) = 只是 c
tuple4 (Tuple1 a) = 无
tuple4 (Tuple2 a b) = 没有
tuple4 (Tuple3 a b c) = 无
tuple4 (Tuple4 a b c d) = Just d

-- 单元测试
prop_tx1 = tuple1 (Tuple1 4) ≡ 仅 4
prop_tx2 = tuple1 (Tuple2 4 'q') ≡ 只有 4
prop_tx3 = tuple2 (Tuple1 4) ≡ (Nothing ∷ Maybe Char)
prop_tx4 = tuple2 (Tuple2 4 'q') ≡ Just 'q'

最佳答案

我会尽量保持简单:

data Tuplex a b c d = Tuple1 a | Tuple2 a b | Tuple3 a b c | Tuple4 a b c d

toMaybes (Tuple1 p) = (Just p, Nothing, Nothing, Nothing)
toMaybes (Tuple2 p q) = (Just p, Just q, Nothing, Nothing)
toMaybes (Tuple3 p q r) = (Just p, Just q, Just r, Nothing)
toMaybes (Tuple4 p q r s) = (Just p, Just q, Just r, Just s)

tuple1 t = p where (p,_,_,_) = toMaybes t
tuple2 t = q where (_,q,_,_) = toMaybes t
tuple3 t = r where (_,_,r,_) = toMaybes t
tuple4 t = s where (_,_,_,s) = toMaybes t

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com